數組排序演算法 (一)冒泡排序 基本思想:對比相鄰的元素值,如果滿足條件就交換元素值,把較小的元素移動數組前面,較大的元素移動到數組後面演算法:冒泡演算法由雙層迴圈實現,其中外層迴圈控制排序輪次,一般為排序的數組長度減一。而內層迴圈主要用於對比數組中每個臨近元素的大小,以確定是否交換位置,對比和交換的次數 ...
數組排序演算法
(一)冒泡排序
基本思想:對比相鄰的元素值,如果滿足條件就交換元素值,把較小的元素移動數組前面,較大的元素移動到數組後面
演算法:
冒泡演算法由雙層迴圈實現,其中外層迴圈控制排序輪次,一般為排序的數組長度減一。而內層迴圈主要用於對比數組中每個臨近元素的大小,以確定是否交換位置,對比和交換的次數隨排序輪數而減少。
演算法實現:
1 public class Bubble { 2 public static void main(String[] args){ 3 int[] array ={63,4,24,1,3,15}; 4 Bubble sorter = new Bubble(); 5 sorter.sort(array); 6 } 7 //冒泡排序 8 public void sort(int[] array){ 9 for(int i=1;i<array.length;i++){ //排序輪次,數組長度-1 10 for(int j=0;j<array.length-i;j++){ //內層比較,每過一輪末尾少比較一個 11 if(array[j]>array[j+1]){ 12 int temp =array[j]; 13 array[j]=array[j+1]; 14 array[j+1]=temp; 15 } 16 } 17 } 18 showArray(array); 19 } 20 //顯示數組元素 21 public void showArray(int[] array){ 22 for(int i:array){ 23 System.out.print(i+" "); 24 } 25 } 26 }
(二)直接選擇排序
速度比冒泡排序快一些
基本思想:將指定排序位置與其他數組元素分別對比,如果滿足條件就交換元素值。
舉例:
初始值:63 4 24 1 3 15
第一輪:15 4 24 1 3 63
第二輪:15 4 3 1 24 63
第三輪:1 4 3 15 24 63
第四輪:1 3 4 15 24 63
第五輪:1 3 4 15 24 63
解釋:首先找出6個數中最大的與最後一個數交換位置,然後在前5個數中找出最大的數與倒數第二個交換位置,這樣length-1次
演算法實現:
1 public class Select { 2 public static void main(String[] args){ 3 int array[]={63,4,24,1,3,15}; 4 Select sorter =new Select(); 5 sorter.sort(array); 6 } 7 //直接選擇排序 8 public void sort(int[] array){ 9 int index; 10 for(int i=1;i<array.length;i++){ //排序輪次仍為數組長度-1 11 index=0; 12 for(int j=1;j<=array.length-i;j++){ //內層比較,找出最大數的位置 13 if(array[j]>array[index]){ 14 index=j; 15 } 16 } 17 int temp=array[array.length-i]; 18 array[array.length-i]=array[index]; 19 array[index]=temp; 20 } 21 showArray(array); 22 } 23 //顯示數組 24 private void showArray(int[] array) { 25 for(int i:array){ 26 System.out.print(i+" "); 27 } 28 } 29 }