public static void quickSort(Integer[] arr, int low, int high)
{
//check for empty or null array
if (arr == null || arr.length == 0){
return;
}
if (low >= high){
return;
}
//Get the pivot element from the middle of the list
int middle = low + (high - low) / 2;
int pivot = arr[middle];
// make left < pivot and right > pivot
int i = low, j = high;
while (i <= j)
{
//Check until all values on left side array are lower than pivot
while (arr[i] < pivot)
{
i++;
}
//Check until all values on left side array are greater than pivot
while (arr[j] > pivot)
{
j--;
}
//Now compare values from both side of lists to see if they need swapping
//After swapping move the iterator on both lists
//NUMBER (1)
if (i <= j)
{
swap (arr, i, j);
i++;
j--;
}
}
//Do same operation as above recursively to sort two sub arrays
//NUMBER (2)
if (low < j){
quickSort(arr, low, j);
}
//NUMBER (3)
if (high > i){
quickSort(arr, i, high);
}
}
我是快速排序算法的初学者。有人可以告诉我条件的目的是什么,如上面的快速排序算法中的数字(1),数字(2)和数字(3)?
对于Number(1),我认为条件不是必需的,因为我肯定会小于或等于j,因此交换应该只执行。
对于数字(2)和数字(3),它是类似的解释。如果我错了,请纠正我,谢谢