I was trying to implement method number 2, from this article.
Method 2 (Use temporary array) K largest elements from arr[0..n-1]
- Store the first k elements in a temporary array temp[0..k-1].
- Find the smallest element in temp[], let the smallest element be min.
- For each element x in arr[k] to arr[n-1] If x is greater than the min then remove min from temp[] and insert x.
- Print final k elements of temp[]
Time Complexity: O((n-k)*k). If we want the output sorted then O((n-k)*k + klogk)
Please comment on the complexity and runtime speed. Can I improve my implementation in that sense? I was trying to get O((n-k)*k).
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace JobInterviewTests
{
//Design an algorithm to find K biggest numbers in the array.
[TestClass]
public class KBiggestNumbers
{
[TestMethod]
public void FindKBiggestNumbersTest()
{
int[] testArray = new[] { 7, 2, 4, 4, 3, 6, 1, 8, 9, 10, 11 };
int k = 5;
int[] result = FindKBiggestNumbers(testArray, k);
int[] expectedResult = new[] { 7,8,9,10,11 };
CollectionAssert.AreEqual(expectedResult, result);
}
private int[] FindKBiggestNumbers(int[] testArray, int k)
{
int[] result = new int[k];
for (int i = 0; i < testArray.Length; i++)
{
//if bigger than the smallest node
if (testArray[i] <= result[0])
{
continue;
}
else
{
//if bigger than all?
if (testArray[i] > result[k - 1])
{
for (int l = 0; l < k - 1; l++)
{
result[l] = result[l + 1];
}
result[k - 1] = testArray[i];
}
else
{
//Naive way
//for (int j = 0; j < k-1; j++)
//{
// if (testArray[i] > result[j] && testArray[i] <= result[j + 1])
// {
// for (int l = 0; l < j; l++)
// {
// result[l] = result[l + 1];
// }
// result[j] = testArray[i];
// break;
// }
//}
//binary search
int indexLeft = 0;
int indexRight = k-1;
int currIndex = 0;
//10 20 30 40 50 - > place 33
while (indexRight- indexLeft >1)
{
currIndex = (indexRight + indexLeft)/2;
if (testArray[i] >= result[currIndex])
{
indexLeft = currIndex;
}
else
{
indexRight = currIndex;
}
}
for (int l = 0; l < currIndex; l++)
{
result[l] = result[l + 1];
}
result[currIndex] = testArray[i];
}
}
}
return result;
}
}
}