gpt4 book ai didi

Java 快速排序帮助

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:16:39 24 4
gpt4 key购买 nike

我正在尝试在 java 中实现快速排序。但是,我遇到了奇怪的行为。我的算法适用于 70 个或更少的项目,但任何高于此的项目都会使整个 Java 应用程序卡住。这是对函数调用的限制还是我正在使用的内存量?

我通常不使用快速排序,所以我的实现可能有点偏差,但我认为总的来说逻辑是正确的:

int data[];

public void QuickSort(int start, int end)
{
if(start == end || end < start || end > data.length)
{
return;
}

//find the pivot
int pivotPos = (int)(start + (end - start) / 2);
int temp;

//switch the pivot to the end
temp = data[pivotPos];
data[pivotPos] = data[end];
data[end] = temp;

int LowerPoint = start;
int HigherPoint = end - 1;

//loop through and move low values down
//and high values up
while(LowerPoint != HigherPoint)
{
while(data[LowerPoint] < data[end] && LowerPoint < HigherPoint)
{
LowerPoint++;
}

while(data[HigherPoint] > data[end] && LowerPoint < HigherPoint)
{
HigherPoint--;
}

if(LowerPoint != HigherPoint)
{
temp = data[HigherPoint];
data[HigherPoint] = data[LowerPoint];
data[LowerPoint] = temp;
}
}

//one last check to make sure we don't swap the pivot with a lower value
//if this value is lower than increment our pointers up so we guarentee
//the swap with a higher value
if(data[LowerPoint] < data[end])
{
LowerPoint++;
HigherPoint++;
}

//place the pivot back to the middle of the list
//by swapping it with the higher point
temp = data[HigherPoint];
data[HigherPoint] = data[end];
data[end] = temp;

this.QuickSort(0, LowerPoint - 1);
this.QuickSort(HigherPoint + 1, end);

}

非常感谢任何帮助。

最佳答案

仔细看下面两行:

    this.QuickSort(0, LowerPoint - 1);
this.QuickSort(HigherPoint + 1, end);

他们有些不太对劲。

关于Java 快速排序帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6326291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com