Here is the description about the algorithm/solution:
- Input: An array of ints and an array index
- Output: Kth largest element of the array
- Read the first K elements into an auxiliary array (the K largest found so far)
- Sort the K-element array
Then:
for each remaining element { if (if it is smaller than the smallest element of the aux. array) { throw it away } else { remove the current smallest element of the auxiliary array place the element into the correct position in the auxiliary array } } then return the smallest (the Kth) element of the auxiliary array
I have come up with the following solution:
public int findElement() throws IndexingError {
int[] bigArray = getArray();
int k = getIndex();
if (k <= 0 || k > bigArray.length) {
throw new IndexingError();
}
int[] smallArray = Arrays.copyOfRange(bigArray,0,k-1);
Arrays.sort(smallArray);
for (int i = k; i < bigArray.length; i++) {
for (int ii = 1; ii < smallArray.length; ii++) {
smallArray[ii-1] = smallArray[ii];
if (bigArray[i] > smallArray[ii]) {
smallArray[ii] = bigArray[i];
System.out.println(smallArray[ii] + " " + smallArray[ii-1] + " " + bigArray[i]);
break;
}
}
}
return smallArray[0];
}
So for example:
The code should return the value of: 8, based on the info below:
array = [2, 3, 8, 7, 1, 6, 5, 9, 4, 0]
k = 2
Running the above code yields different outputs every time, if you run it enough times you get the correct answer?
Could someone identify/fix flaws in my code?
kelements in it in a sorted fashion. So you can just use any sorting algorithm but change it a bit to place elements in the second array and restrict it tokelements. For instance with bubble sort find only firstkelements and place ones or element indexes into the second array