简体   繁体   English

第K个最小元素算法

[英]Kth smallest element algorithm

I'm writing an algorithm that divides and conquers an unsorted array of integers to find the kth smallest element. 我正在编写一种算法,该算法可以对未排序的整数数组进行分而治之,以找到第k个最小的元素。 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. 谢谢。

You will go wrong for the input 1,2,3,20,4,5,6 and searching for the 6th element. 输入1,2,3,20,4,5,6并搜索第6个元素会出错。 That is because in this case you will have to swap an element more than once and it seems to me you never do that. 这是因为在这种情况下,您将不得不多次交换一个元素,而在我看来,您永远不会那样做。 You will swap 20 and 6 but after that you will increase i and thus will never swap 6 again while you actually should. 您将交换20和6,但是之后您将增加i,因此在您本应实际使用时再也不会交换6。 6 is the correct answer. 6是正确答案。 I am not sure what value you would find but it will not be 6. 我不确定您会找到什么价值,但不会是6。

Also several problems may happen because of elements equal to the pivot. 同样,由于元素等于枢轴,可能会发生一些问题。 Try adding special checks for such elements. 尝试为此类元素添加特殊检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM