在快速排序中使用随机轴,Java

在快速排序中使用随机轴,Java,java,quicksort,Java,Quicksort,我的代码几乎正常工作,给了我一个几乎分类的数据。 cmp(i,j)方法在ii时返回正值 代码: public void sort(){ sortQuick(0, getElementCount()-1); } public void sortQuick (int first, int last){ // pivot tilldelas ett värde mellan noll och antal element i vektorn. final Random rand

我的代码几乎正常工作,给了我一个几乎分类的数据。
cmp(i,j)
方法在i时返回负值
,在j>i
时返回正值

代码:

public void sort(){ 
    sortQuick(0, getElementCount()-1);
}
public void sortQuick (int first, int last){
    // pivot tilldelas ett värde mellan noll och antal element i vektorn.
    final Random random = new Random();
    System.out.println(("Last: " + last + ", first : " + first));
    int up = first;                          
    int down = last; 

    int pivot = random.nextInt(last-first) + first;
    System.out.println(pivot);                          
    while (up < down ) {

        while (cmp(up,pivot) < 0) {
            up++;
        }
        while (cmp(down,pivot) > 0) {
            down--;
        }
        if (up <= down) {
            swap(up,down);
            up++;
            down--;
        }
    }
    if (down > first) {
        sortQuick(first, down);
    }
    if (last > up) {
        sortQuick(up, last);
    }
}
public void sort(){
sortQuick(0,getElementCount()-1);
}
public void sortQuick(int first,int last){
//支点蒂尔德拉·埃特·瓦尔德·梅兰·诺尔·奥赫·安塔尔元素一维克顿。
最终随机数=新随机数();
System.out.println(((“Last:+Last+”,first:+first));
int up=第一;
int down=最后一个;
int pivot=random.nextInt(last-first)+first;
系统输出打印项次(枢轴);
while(向上<向下){
同时(凸轮轴位置(向上,枢轴)<0){
up++;
}
同时(凸轮轴位置(向下,枢轴)>0){
向下--;
}
如果(先上){
sortQuick(第一,向下);
}
如果(上一个>上一个){
sortQuick(向上,最后);
}
}

建议?

问题在于您只存储pivot元素的索引,而不存储实际值

如果稍后在算法中,
up
(或
down
)恰好达到值
pivot
,并进行交换,则索引
pivot
处的值将发生变化。因此,随后的比较将针对不同的pivot元素

记住轴值并与之进行所有比较,如:

int pivotIndex = random.nextInt(last-first) + first;
int pivotValue = getValueAt(pivotIndex);

while (up < down ) {

    while (getValueAt(up) < pivotValue) {
        up++;
    }
    while (getValueAt(down) > pivotValue) {
        down--;
    }
    if (up <= down) {
        swap(up,down);
        up++;
        down--;
    }
int pivotIndex=random.nextInt(last-first)+first;
int pivotValue=getValueAt(pivotIndex);
while(向上<向下){
while(getValueAt(up)数据透视值){
向下--;
}

if(数据存储在哪里?我看不到任何关于数组或列表的提及?将您的代码与以下内容进行比较:您是否有一个测试输入,您的排序算法只生成一个“几乎”排序的输出?Tyler:数据存储在其他类中,该类调用了其他类。Graham:猜猜我做了什么;)。仍然不起作用。是的,我会。如果我使用它,它将完全排序。此外,如果我运行两次快速排序(有时是trice)在我想要排序的数字向量上,它会得到完美的排序。我已经运行了几个测试用例,结果总是很好地排序。也许错误不在这段代码中,而是在cmp/swap中?好吧。我真的不明白如何实现它。你能给我一个代码示例吗?好的,我丰富了我的答案,为你提供了一些我想要的答案缉毒局,这很有效!你就是那个人,伙计!如果我知道怎么做,我会打败你的!
    if (up <= down) {
        swap(up,down);
        if(pivot == up) { pivot = down; }
        else if(pivot == down) { pivot = up; }
        up++;
        down--;
    }