我正在对从文件中读取的 2000 个整数进行快速排序,但我得到的比较和交换次数似乎很高。我的柜台在正确的地方吗?还是排序有问题?
public int partition(int array[], int low, int high)
{
int pivot = array[high];
int i = (low-1);
for (int j = low; j < high; j++)
{
compCounter++;
if (array[j] <= pivot)
{
i++;
int temp = array[i];
array[i] = array[j];
array[j] = temp;
SwapCounter++;
}
}
int temp = array[i+1];
array[i+1] = array[high];
array[high] = temp;
SwapCounter++;
return i+1;
}
public void quickSort(int array[], int low, int high)
{
if (low < high)
{
int pivotPoint = partition(array, low, high);
quickSort(array, low, pivotPoint-1);
quickSort(array, pivotPoint+1, high);
}
}
最佳答案
您的计数器是正确的。
只是一个快速建议 - 将交换代码移动到单独的函数 swap(array, fromIndex, toIndex)
关于java - 计算快速排序中的比较和交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52616840/