在数据透视分区数组数组、分区、透视、数据

2023-09-11 23:17:57 作者:不拽怎么赢世界

我试图编写一个简单的算法,用于移动围绕枢轴的元件,使得在枢左侧的元素比枢轴和枢轴右侧的元件越小大于它(在快速排序同一步骤)。我已经写了code这样的作品,但在那之后,我改变了算法的下方,这是行不通的。

I am trying to write a simple algorithm for moving the elements around pivot such that the elements on the left of pivot is smaller than the pivot and the element on the right of pivot is greater than it (the same step in quick sort). I have written code that works, but after that I changed the algorithm to the below, and it is not working.

该算法的思想是简单

有两个指针,一个在数组的开始,一个在数组的末尾。如果所指向我的元素比支点较小,保持跳过它,直到我们找到一个更大的单元;并保持递减Ĵ,直到我们找到一个元素大于更小的元素。 [它是一种常见的算法]

Have two pointers, one at the beginning of the array and one at the end of array. If the elements pointed by i are lesser than pivot, keep skipping it until we find a greater element; and keep decrementing j until we find an element greater than the smaller element. [It is a common algorithm]

现在code

private  static void sortByPivot(int[] a)
{

    Random r = new Random();
    int index = r.nextInt(a.length);
    int pivot = a[index];

    System.out.println("pivot = " + pivot);

    int i =0 , j = a.length -1;

    while(true)
        {

            while(a[i] <= pivot) i++;

            while( j >0 && a[j] >= pivot) j--;

            if(i <= j)
            {
                break;
            }
            else{
                swap(a,i,j);
               }

        }

        swap(a,i,index); //swap the pivot and the i
}

交换程序:

private static void swap(int[] a, int i , int j)
{
    int temp = a[i];
    a[i] = a[j];
    a[j] = temp;
}

当我运行用下面的数组

  int[] a = {46,3,8,4,2,6,244,76} 

和当枢轴拾取作为4 输出

and when the pivot is picked as 4 the output is

         4 3 8 46 2 6 244 76 

对于一些其他的支点是在边缘,我得到一个空指针异常。

For some other pivots that are in the edge, I get a null pointer exception.

有没有执行中的任何缺陷。逻辑似乎是我的权利。我一直在尝试它相当一段时间,但我不能修复它。

Is there any flaw in the implementation. The logic seems right to me. I have been trying it for quite sometime but I am unable to fix it.

推荐答案

勾选此的实施。它的工作原理完全同样的原则。尝试比较,看看你要去哪里错了。

Check this implementation. It works exactly on the same principle. Try to compare and see where you are going wrong.

请注意,您应该如果 I&LT; = j的,也从环打破。你正在做的一样,这是不对的,因为如果 A [1] 大于支点和 A [J] 小于枢轴由你到达的时间,如果,那么他们应该被交换,如果 I&LT;。= j的

Note that you are supposed to swap the values of a[i] and a[j] if i <= j and also break from the loop. You are doing it on the else, which is wrong, because if a[i] is greater than the pivot and a[j] is less than the pivot by the time you reach the if, then they should be swapped if i <= j.