快速排序
python版本
def partition(arr, low, high):
left = low # 最小元素索引
pivot = arr[high]
for j in range(low, high):
# 当前元素小于或等于 pivot
if arr[j] <= pivot:
arr[left], arr[j] = arr[j], arr[left]
left += 1
arr[left], arr[high] = arr[high], arr[left]
return left
# arr[] --> 排序数组
# low --> 起始索引
# high --> 结束索引
# 快速排序函数
def quickSort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quickSort(arr, low, pi - 1)
quickSort(arr, pi + 1, high)
arr = [10, 7, 8, 9, 1, 5]
quickSort(arr, 0, len(arr) - 1)
print(arr)
java版
/**
* @Description
* 快速排序 参考视频:https://www.bilibili.com/video/av39519566/
* @Author 田云
* @Date 2019/6/10 11:14
* @Version 1.0
*/
public class QuickSort {
public static void main(String[] args) {
int[] array = {2, 4, 6, 8, 5, 4, 6, 2, 6};
quickSort(array, 0, array.length - 1);
for (int i : array) {
System.out.println(i);
}
}
public static void quickSort(int[] array, int left, int right) {
if (left >= right) {
return;
}
int base = array[left];
int i = left;
int j = right;
while (i != j) {
while (array[j] >= base && i < j) {
j--;
}
while (array[i] <= base && i < j){
i++;
}
/**
* 交换
*/
int tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
array[left] = array[i];
array[i] = base;
quickSort(array, left, i - 1);
quickSort(array, i + 1, right);
}
}