快速排序
java
算法思想:从待排序记录系列中选取一个记录(通常选取第一个记录)为枢轴,其关键字设为K1;然后将其与关键字小于k1的记录移到前面,而将关键字大于或等于K1的记录移到后面,结果将待排序记录序列分成两个子表,最后将关键字为K1的记录插到其分界线的位置处。将这个过程称为一趟快速排序。通过一次划分后,就以关键字为K1的记录为界,将待排序序列分成两个子表,且前面子表中所有记录的关键字均小于K1,而后面子表中的所有记录的关键字均大于K1.对分割后的子表继续按上诉原则进行分割,直到所有子表的表厂不超过1为止。
算法步骤:假设带划分序列为a[low]…a[high]。首先将基准记录a[low]移至变量x中,使r[low]相当于空单元,然后反复进行如下两个扫描过程,知道low和high相遇。
1.high从右向左扫描,直到a[high]<x时,将a[high]移至a[low],此时a[high]相当于空单元。
2.high从左向右扫描,直到a[low]>=x时,将a[low]移至a[high],此时a[low]相当于空单元。
当low和high相遇时,alow相当于空单元,且a[low]左边所有记录的关键字均小于基准记录的关键字,而a[low]右边所有记录的关键字均大于或等于基准记录的关键字。最后将基准记录移至a[low]中,就完成了一次划分过程。对于a[low]左边的子表和a[low]右边的子表可采用同样的方法进行进一步划分。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package paixu;
public class PaiXu {
public static void main(String[] args) {
int []a={48,62,35,77,55,14,35,98};
QKSort(a,0,a.length-1);
for(int i=0;i<a.length;i++){
System.out.println(a[i]);
}
}
public static void QKSort(int[] a,int low,int high) {
if(low<high){
int pos=QKPass(a,low,high);
QKSort(a,low,pos-1);
QKSort(a,pos+1,high);
}
}
private static int QKPass(int[] a, int low, int high) {
int x=a[low];
while(low<high){
while(low<high&&a[high]>=x){
high--;
}
if(low<high){
a[low]=a[high];
low++;
}
while(low<high&&a[low]<x){
low++;
}
if(low<high){
a[high]=a[low];
high--;
}
}
a[low]=x;
return low;
}
}