排序算法之快速排序
算法描述:
通过一趟排序使待排记录分割成两个独立的两部分,其中左侧的部分都小于基准值,二右侧的部分都大于基准值,接着再分别对两部分进行快速排序(当low=high),以达到整个序列有序
算法描述,挑选第一个元素基准值,
①先从队尾开始向前扫描且当low < high时,如果a[high] > tmp,则high–,但如果a[high] < tmp,则将high的值赋值给low,即arr[low] = a[high],同时要转换数组扫描的方式,即需要从队首开始向队尾进行扫描了
②同理,当从队首开始向队尾进行扫描时,如果a[low] < tmp,则low++,但如果a[low] > tmp了,则就需要将low位置的值赋值给high位置,即arr[low] = arr[high],同时将数组扫描方式换为由队尾向队首进行扫描.
③不断重复①和②,知道low>=high时(其实是low=high),low或high的位置就是该基准数据在数组中的正确索引位置
代码实现;
public class QuickSort {
public static void main(String[] args) {
int[] a={19,98,19,96,12,2,3,2,45,96,71};
System.out.println("未排序之前的序列");
for(int s:a){
System.out.println(s);
}
quick(a,0,a.length-1);
System.out.println("排序之后的序列");
for(int s:a){
System.out.println(s);
}
}
private static void quick(int[] a, int low ,int high) {
if(low<high){
int index=sorrt(a,low,high);
quick(a,low,index-1);
quick(a,index+1,high);
}
}
private static int sorrt(int[] a, int low, int high) {
int temp=a[low];
int i=low ;
int j=high;
while(i<j){
while(a[j]>=temp&&j>i){
j--;
}
a[i]=a[j];
while(a[i]<=temp&&i<j){
i++;
}
a[j]=a[i];
}
a[i]=temp;
return i;
}
}