【发布时间】:2016-04-25 12:29:06
【问题描述】:
我是 C++ 新手,正在经历来自 http://geeksquiz.com/quick-sort/ 的一种快速排序算法
这里是sn-p的代码,我无法理解low和high的值怎么变了
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void quickSort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
请帮我理解上面的逻辑。
【问题讨论】:
-
理解这个逻辑的最好方法是拿出一张纸和一支铅笔,写下一个小数组,比如五个元素。然后,一次一行地浏览
partition()中的代码,跟踪每个变量和数组的内容。 -
low和high只是递归排序的边界 -
@SamVarshavchik 我可以理解 partition() 背后的逻辑。我无法理解的一件事是递归逻辑和低值更新。由于函数中没有我们正在更新低/高的值。