快速排序,顾名思义,在各种排序算法中,快速排序算法综合性能最为优异。所以掌握快速排序是一个程序员的基本功。
首先写出我的实现思路,本文采用Java语言,C/C++代码类似:
Step 0 : thinking
public class quickSortDemo{
public static void main(String args[]){
//define a test array
//invoke the quickSort()
//print the array after it was sorted
}
//function quickSort()
public void quickSort(int array[],int left,int right){
//do nothing if left >= right
//invoke the partition()
//recursive quickSort() the left parts and right parts
}
//function partition()
public int partition(int array[],int left,int right){
//p<-get a number from array
//put elements <= p to the left side
//put elements >= p to the right side
//put p in the middle slot which index id pivot
}
}
Step 1 : encoding
public int partition(int array[],int left,int right){
//p<-get a number from array
int p = array[left];
int i = left;
int j = 0;
for(j=i+1;j<=right;j++){
//put elements <= p to the left side
//put elements >= p to the right side
if(p>array[j]){
i++;
swap(array,i,j);
}
}
//put p in the middle slot which index id pivot
swap(array,i,left);
return i;
}
public void quickSort(int array[],int left,int right){
//do nothing if left >= right
if(left<right){
//invoke the partition()
int pivot = partition(array,left,right);
//recursive quickSort() the left parts and right parts
quickSort(array,left,pivot-1);
quickSort(array,pivot+1,right);
}
}
Step 2 : add function swap()
//it's main function is to exchange number
public void swap(int array[],int i,int j){
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Step 3 : test the class
public class Demo{
public static void main(String args[]){
int temp[] = {3,8,6,4,5,6,1,9,2,0,22,22,22,33,454,5,4,3333,22222};
new Demo().quickSort(temp,0,temp.length-1);
for(int i=0;i<temp.length;i++){
System.out.print(temp[i]+"、");
}
System.out.println();
}