思想:
每次确定要排序列表中一个元素的绝对位置,而后将该列表划分为两部分,两部分分别按照同样的方式进行排序。
C代码
#include "stdio.h"
void array_print(int a[],int n );
void sort_quick(int a[],int start,int end);
int partition(int a[], int start,int end);
void swap(int a[],int s,int t);
void main(){
int a[]={3,1,18,30,12,11,18,43};
int n = sizeof(a)/sizeof(int);
sort_quick(a,0,n-1);
array_print(a,n);
}
void sort_quick(int a[],int start,int end){
int m ;
if(start < end ){
m = partition(a,start,end);
sort_quick(a,start,m-1);
sort_quick(a,m+1,end);
}
}
int partition(int a[],int start,int end){
int x = a[end];
while(start < end){
while(start<end && a[start]<= x) start++;
if(start == end) break;
swap(a,start,end);
end -- ;
while(start<end && a[end] >= x) end--;
if(start == end ) break;
swap(a,start,end);
start ++;
}
return start;
}
void array_print(int a[],int n ){
int i;
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
void swap(int a[],int s,int t){
int x = a[s];
a[s] = a[t];
a[t] = x;
}
JAVA代码
import java.util.List;
public class SortQuick implements Sort {
@Override
public void sort(List<Integer> source) {
sort_quick(source, 0, source.size()-1);
}
private void sort_quick(List<Integer> source, int low ,int high){
if(low < high){
int m = partition(source, low, high);
sort_quick(source, low, m-1);
sort_quick(source, m+1, high);;
}
}
private int partition(List<Integer> source, int low,int high){
int x = source.get(low);
while(low<high){
while(low<high && source.get(high)>=x) high--;
swap(source, low,high);
while(low<high && source.get(low)<=x) low++;
swap(source,low,high);
}
return low;
}
private void swap(List<Integer> source,int a,int b){
int x = source.get(a);
source.set(a, source.get(b));
source.set(b, x);
}
}