I'm writing an algorithm that divides and conquers an unsorted array of integers to find the kth smallest element. When testing my program, a couple of my outputs came out wrong. Here is the code:
public class kthsmallest {
public static final int MaxSize = 500;
public static int find_kth_smallest( int[] A, int n, int k )
{
return quicksort(A, n, k, 0, n-1);
}
public static int quicksort(int[] A, int n, int k, int low, int high){
int i = low;
int j = high;
int position = low + (high-low)/2;
int pivot = A[position];
while (i <= j){
while(A[i] < pivot)
i++;
while(A[j] > pivot)
j--;
if (i <= j){
int temp = A[i];
A[i] =A[j];
A[j] = temp;
i++;
j--;
}
}
//
if (position + 1 > k){
return quicksort(A, n, k, low, position-1);
} else if (position + 1 < k){
return quicksort(A, n, k, position+1, high);
} else
return A[position];
If anyone can see anything wrong with this algorithm, please let me know. I've been debugging for hours. Thanks.