快速排序
不稳定排序
空间复杂度:O(递归层数) ;最好空间复杂度:O(log(底数为2)n) ; 最坏空间复杂度 :O(n)
时间复杂度:O(n*递归层数) ;最好时间复杂度:O(nlog(底数为2)n) ;最坏时间复杂度: O(n²)
递归层数: 把n个元素组成排序二叉树,二叉树的层数就是递归调用的层数
n个节点的二叉树最小高度为[log(底数为2)n]+1 最大高度=n
public static void main(String[] args) {
int[] ary= {49,38,65,97,76,13,27,49,90};
QuickSort(ary,0,ary.length-1);
for (int x : ary) { //遍历ary数组
System.out.print(x+ " ");
}
}
private static void QuickSort(int[] ary,int low, int high) {
if(low<high){
int pviotIndex = partition(ary,low,high); //枢轴存放的位置索引
QuickSort(ary, low,pviotIndex-1); //对枢纽元素左边元素进行递归调用
QuickSort(ary, pviotIndex+1,high);//对枢纽元素右边元素进行递归调用
}
}
private static int partition(int[] ary,int low, int high) {
int pviot = ary[low]; //将第一个元素作为枢轴
while (low<high){ //用low high 搜索枢轴最终位置
while (low<high&&ary[high]>=pviot){
high--;
}
ary[low] = ary[high]; //比枢轴小的移动到左边
while (low<high&&ary[low]<pviot){
low++;
}
ary[high] = ary[low]; //比枢轴大的移动到左边
}
ary[low] = pviot; //枢轴存放的最终位置
return low;
}
}