一、快排介绍
不懂基本原理的可以看一下百度百科-快速排序。有两种实现方式,一种是使用partition函数;另外就是普通的
二、Java 代码
//使用partition方法
public void quickSort(int[] nums, int low, int high){
if (nums==null || nums.length==0 || low > high) {
return ;
}
int idx = partition(nums, low, high, low);
quickSort(nums, low, idx-1);
quickSort(nums, idx+1, high);
}
public int partition(int[] nums, int low, int high, int pivotIdx){
int pivot = nums[pivotIdx];
swap(nums, pivotIdx, high);
int startIdx = low;
for (int i = low; i < high; i++) {
if (nums[i]<pivot) {
swap(nums, i, startIdx);
startIdx++;
}
}
swap(nums, startIdx, high);
return startIdx;
}
private void swap(int[] nums, int a, int b){
int tmp = nums[a];
nums[a] = nums[b];
nums[b] = tmp;
}
//一般快排
public void quickSort2(int[] arr, int left, int right) {
if (left >= right) {
return;
}
int low = left;
int high = right;
int key = arr[low];
while (low < high) {
while (low < high && arr[high] >= key)
high--;
if (low<high) {
arr[low++] = arr[high];
}
while (low < high && arr[low] <= key)
low++;
if (low<high) {
arr[high--] = arr[low];
}
}
arr[low] = key;
quickSort(arr, left, low - 1);
quickSort(arr, low + 1, right);
}