【算法】java实现快速排序

快速排序(Quicksort)是对冒泡排序的一种改进。 快速排序由C. A. R.
Hoare在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。

java代码

public class QuickSortMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[]={1,32,24,55,6,85,22};
		quickSort(a, 0, a.length-1);
	}

	public static void quickSort(int[] a,int start,int end){
		//记录头尾位置
		int low = start;
        int high = end;
        //选取头作为关键值
		int key=a[start];
		while(start<end){
			//从后向前找出小于关键值的数进行交换
			while(start<end&&a[end]>=key)
				end--;
			if(a[end]<key){
				int temp=a[start];
				a[start]=a[end];
				a[end]=temp;
			}
			//从前向后找出大于关键值的数进行交换
			while (start<end&&a[start]<=key)
				start++;
			if(a[start]>key){
				int temp=a[start];
				a[start]=a[end];
				a[end]=temp;
			}
		}
		 for(int i = 0; i<a.length; i++){
             System.out.print(a[i]+",");
         }
		 System.out.println("\n");
		 //递归
         if(start>low) quickSort(a, low, start-1);//左边序列。第一个索引位置到关键值索引-1
         if(end<high) quickSort(a, end+1,high);//右边序列。从关键值索引+1到最后一个	
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章