首先,上腦圖。面試
一、爲何要學習排序算法?算法
這是算法學習的基礎,經典的排序算法有着很普遍的用途,一遍遍的被人所使用。並且,在面試找工做的時候,數據結構中的排序算法,也是一個很重要的基本功,常常會被用人單位拿來出題目。數組
二、如何學習排序算法?數據結構
第一步是理解排序算法的原理,這也是最重要的一步。學習
第二步就是看經典的算法實現,摳細節一個個理解原理到實現通過了哪些變化。ui
第三部是用紙把算法實現抄一遍,這個時候會發掘出認識和實際的誤差。spa
第四步是把算法默寫出來,這也是很重要的一步,相似於牛吃了食物以後的反芻過程,會進一步加深對於算法的理解。code
第五步,將算法代碼用各類語言實現出來,而且體會不一樣語言實現起來的差別。blog
第六步就是作總結和分享,進一步加深印象,並有助於之後再回過頭來看。排序
三、交換排序算法原理分析
比較典型的交換排序算法有兩個,分別是冒泡排序和快速排序。冒泡排序,主要的思想爲每次排好一個最大的(或最小的)數,而後在剩下的數據裏面繼續這個排序最大數(最小數)的過程,直到全部數據都有序爲止。冒泡排序的時間複雜度是O(n2)。冒泡排序的特色是,實現簡單,可是效率低下。
快速排序,主要的思想爲每次挑選一個數,和剩下的數依次作比較,比這個數要大的數據放在這個數據的後面位置,比這個數小的放在前面的位置。一輪事後,就找到這個數在全體數據中的位置。接下來,用一樣的方法分別遞歸這個數的左邊和右邊。最後獲得一個有序數組。快速排序的時間複雜度爲O(n logn)。快速排序的特色是,實現複雜,時間複雜度低。
最後,上代碼,先是冒泡排序:
1 public class Maopao { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 int num[]={10,9,8,7,6,5,4,3,2,1}; 9 new Maopao().maopao(num); 10 for(int i=0;i<num.length;i++){ 11 System.out.print(num[i]+","); 12 } 13 } 14 public void maopao(int num[]){ 15 int i,j,temp; 16 for(i=0;i<num.length-1;i++){ 17 for(j=0;j<num.length-1-i;j++){ 18 if(num[j]>num[j+1]){ 19 temp=num[j]; 20 num[j]=num[j+1]; 21 num[j+1]=temp; 22 } 23 } 24 } 25 } 26 27 }
而後是快排:
1 public class Qsort { 2 3 /** 4 * @param args 5 */ 6 public static void main(String[] args) { 7 // TODO Auto-generated method stub 8 int num[]={0,10,9,8,7,6,5,4,3,2,1}; 9 new Qsort().Qsot(num); 10 for(int i=1;i<num.length;i++){ 11 System.out.print(num[i]+","); 12 } 13 } 14 int partition(int num[],int low,int high){ 15 num[0]=num[low]; 16 int p=num[low]; 17 while(low<high){ 18 while(low<high && num[high]>=p)high--; 19 num[low]=num[high]; 20 while(low<high && num[low]<=p)low++; 21 num[high]=num[low]; 22 } 23 num[low]=num[0]; 24 return low; 25 } 26 public void QuickSort(int num[],int low,int high){ 27 if(low<high){ 28 int p = partition(num,low,high); 29 QuickSort(num,p+1,high); 30 QuickSort(num,low,p-1); 31 } 32 } 33 public void Qsot(int num[]){ 34 QuickSort(num,1,num.length-1); 35 } 36 }