快速排序的思想其实很简单就是从一堆数中,先找出一个benchmark(基准){可以是第一个元素也可以是最后一个元素},然后把小于他的数字排到他的左边,大于他的数字排到他的右边
我现在画一个快排的流程图
你会发现每次排序都会使得一个数字在他应该在的位置
其实快排也是运用了分治的思想,先将一个数拍到他应该在的位置,然后排他左边的排他右边的,递归下去,递归的出口就是low = high
所以我们可以写出递归的代码
public static void Quick_sort(int[] array,int low,int high){
if(low < high){
int temp = select(array,low,high);
Quick_sort(array,low,temp - 1);
Quick_sort(array,temp + 1,high);
}
}
这里的select就是把小于基准的数排到左边大于基准的数排到右边的函数
public static int select(int[] array,int low,int high){
int pivot = high;
int i = low;
int j = low;
while (j < pivot){
if(array[j] > array[pivot]){
j += 1;
}
if(array[j] < array[pivot]){
Swap(array,i,j);
i++;
j++;
}
}
Swap(array,i,pivot);
return i;
}
总代码:
import java.util.Scanner;
//TIP 要<b>运行</b>代码,请按 <shortcut actionId="Run"/> 或
// 点击装订区域中的 <icon src="AllIcons.Actions.Execute"/> 图标。
public class Main {
public static void Swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static int select(int[] array,int low,int high){
int pivot = high;
int i = low;
int j = low;
while (j < pivot){
if(array[j] > array[pivot]){
j += 1;
}
if(array[j] < array[pivot]){
Swap(array,i,j);
i++;
j++;
}
}
Swap(array,i,pivot);
return i;
}
public static void Quick_sort(int[] array,int low,int high){
if(low < high){
int temp = select(array,low,high);
Quick_sort(array,low,temp - 1);
Quick_sort(array,temp + 1,high);
}
}
public static void main(String[] args) {
int[] a = {4,1,2,6,3,9,5};
Quick_sort(a,0,6);
for(int i =0;i < 7;i++) {
System.out.print(a[i]);
System.out.print('\t');
}
}
}