思路:
选择一个基准值array[(startIndex + endIndex) / 2],比基准值小的挪到左边,比基准值大的挪到右边。
对左边、右边,再分别用递归进行这种处理。
基准值可以取array[0],但如果数组为已经逆序排序,快速排序的效率就会变成冒泡排序。
快速排序在最糟糕的情况下,效率等于冒泡排序。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| fun quickSort(array: IntArray, startIndex: Int, endIndex: Int) { if (startIndex >= endIndex) { return }
var leftIndex = startIndex var rightIndex = endIndex val middleValue = array[(leftIndex + rightIndex) / 2]
while (leftIndex <= rightIndex){ while (array[leftIndex] < middleValue){ ++leftIndex }
while (array[rightIndex] > middleValue){ --rightIndex }
if (leftIndex < rightIndex){ val tmp = array[leftIndex] array[leftIndex] = array[rightIndex] array[rightIndex] = tmp
++leftIndex --rightIndex
}else if (leftIndex == rightIndex){ ++leftIndex }
}
quickSort(array,startIndex,rightIndex) quickSort(array,leftIndex,endIndex)
}
|
## dart实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| quickSort(List<int> list,int beginIndex,int endIndex){ if(beginIndex >= endIndex || list.isEmpty){ return; }
int middle = list[(beginIndex+endIndex)~/2]; int leftIndex = beginIndex; int rightIndex = endIndex;
while(leftIndex <= rightIndex) {
while (list[leftIndex] > middle) { ++leftIndex; }
while (list[rightIndex] < middle) { --rightIndex; }
if (leftIndex < rightIndex) { int tmp = list[leftIndex]; list[leftIndex] = list[rightIndex]; list[rightIndex] = tmp; ++leftIndex; --rightIndex; } else if (leftIndex == rightIndex) { ++leftIndex; } } quickSort(list, leftIndex, endIndex); quickSort(list, beginIndex, rightIndex);
}
|