/*
1)选择一个基准元素,通常选择第一个元素或者最后一个元素,
2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。
3)此时基准元素在其排好序后的正确位置
4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。
1)选择一个基准元素,通常选择第一个元素或者最后一个元素,
2)通过一趟排序讲待排序的记录分割成独立的两部分,其中一部分记录的元素值均比基准元素值小。另一部分记录的 元素值比基准值大。
3)此时基准元素在其排好序后的正确位置
4)然后分别对这两部分记录用同样的方法继续进行排序,直到整个序列有序。
*/
import java.util.*;
class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
System.out.print("Input n : ");
int n=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
quickSort(a,0,a.length-1);
print(a);
}
public static void quickSort(int[] a,int low,int high){
int key=a[low],temp,low1=low,high1=high;
while(low1<high1){/*控制在当组内寻找一遍*/
while(low1<high1&&a[high1]>=key){
/*而寻找结束的条件就是,1,找到一个小余或者大于key的数(大小取决于你想升
序还是降序)2,没有符合的切i与j相遇*/
high1--;/*向前寻找*/
}
/*找到一个这样的数后就把它赋给前面的被拿走的i的值(如果第一次循环且key是
a[0],那么就是给key)*/
if(low1<high1){
temp=a[low1];a[low1]=a[high1];a[high1]=temp;
low1++;
}
/*这是i在当组内向前寻找,同上,不过注意与key的大小关系停止循环和上面相反,
因为排序思想是把数往两边扔,所以左右两边的数大小与key的关系相反*/
while(low1<high1&&a[low1]<=key){
low1++;
}
if(low1<high1){
temp=a[low1];a[low1]=a[high1];a[high1]=temp;
high--;
}
}
if(low1>low){
quickSort(a,low,high1-1);
}
if(high1<high){
quickSort(a,low+1,high);
}
}
public static void print(int[] a){
for(int i=0;i<a.length-1;i++){
System.out.print(a[i]+" ");
}
System.out.println(a[a.length-1]);
}
}