經典排序之快速排序

快速排序堪稱最經典的排序,思想是選一個基準值,一般選第一個。然後所有的值與基準值比較,大的位置不變,

小的位置與第一個大的位置互換,就這樣進行第一輪排序,然後對於基準值二邊的再進行排序,依次類推,直到爲剩一個。

下面是快排的代碼:

public class QuickSort {
    
	public void quickSort(int a[],int start,int end){
		//比較這個數組是否只有一個值沒有進行快速排序		
		if(start<end){
		   
		   //基準值
		   int keyword=a[start];
		   int i=start;	
		   
		   for(int j=i+1;j<=end;j++){
			   //與基準值比較,大的位置不變,小的與第一個大的交換
			   if(a[j]<keyword){
				   int temp=a[j];
				   a[j]=a[i+1];
				   a[i+1]=temp;
				   i++;
			   }		       
		   }	
		   a[start]=a[i];
		   a[i]=keyword;
		   //以此類推,遞歸的對所有的進行快排
		   quickSort(a, start, i-1);
		   quickSort(a, i+1, end);
		}
		
		
	}
	
	public static void main(String[] args){
		
		Random random=new Random();
		int[] a=new int[10000];
		for(int i=0;i<a.length;i++){
			a[i]=random.nextInt(10000);
		}
		
		long startTime=System.currentTimeMillis();
		QuickSort quickSort=new QuickSort();
		quickSort.quickSort(a, 0, a.length-1);
		long endTime=System.currentTimeMillis(); 
	    System.out.println("程序運行時間: "+(endTime-startTime)+"ms");
	    
	    //排序後的序列
	    System.out.println("排序後的序列:");
		for(int i=0;i<a.length;i++){
			System.out.println(a[i]);
		}
		
	}
	
}

代碼很簡單,不多說了

發佈了39 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章