快速排序
快速排序的基本思想是基于 分治法 的。
快速排序是 所有内部排序算法中平均性能最优的排序算法。
时间复杂度
最好情况:O(n log2n)
最坏情况:O(n2)
平均情况:O(n log2n)
空间复杂度
快速排序是递归调用的,因此需要一个递归栈,来保存每次递归的有用的信息。
最好情况:O(log2n)
最坏情况:O(n)
平均情况:O(log2n)
稳定性
左右区间元素的相对位置会变化,不稳定!
适用性
顺序存储(链式存储)
代码
import java.util.Scanner;
public class Quick {
public static void sort(int []list,int low,int high) {
if(low<high) {
int position=partition(list, low, high);
sort(list,low,position-1);
sort(list,position+1,high);
}
}
public static int partition(int []list,int low,int high) {
int pivot=list[low];
while(low<high) {
while(low<high && list[high]>=pivot) {
high--;
}
list[low]=list[high];
while(low<high && list[low]<=pivot) {
low++;
}
list[high]=list[low];
}
list[low]=pivot;
return low;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] list = new int[n];
for (int i = 0; i < n; i++) {
list[i] = sc.nextInt();
}
int low=0;
int high=list.length-1;
sort(list,low,high);
for(int i=0;i<n;i++) {
System.out.print(list[i]+" ");
}
sc.close();
}
}