java冒泡排序

記得有一次筆試要寫一個冒泡排序,一會兒就懵了,雖然上學時有開過算法與結構的課,但基本都在打盹,根本就沒有了解過其排序原理。好吧,之前的瀟灑,如今的苦逼,趁失眠時間瞭解一下冒泡排序。html

網上概念一大堆,良莠不齊,最後寫出來了,並能夠升序排序。但對比了網上寫的排序發現本身寫的每一趟都比較到最後一個元素,多是對概念沒理解透徹吧(自我安慰一下)。後來發現這個博客描述寫的挺好的:http://www.cnblogs.com/kkun/archive/2011/11/23/2260280.html,但感受他的代碼邏輯有點不正確,並且評論也有這樣的反饋因此就不貼了,有興趣的朋友能夠前去了解。算法

博客上的簡要描述數組

原理:比較相鄰的元素。若是第一個比第二個大,就交換他們兩個,按照從小到大或者從大到小的順序進行交換,這樣一趟過去後,最大或最小的數字被交換到了最後一位,ide

而後再從頭開始進行兩兩比較交換,直到倒數第二位時結束。spa

例子爲從小到大排序,code

原始待排序數組| 6 | 2 | 4 | 1 | 5 | 9 |htm

 

第一趟排序(外循環)blog

第一次兩兩比較6 > 2交換(內循環)排序

交換前狀態| 6 | 2 | 4 | 1 | 5 | 9 |博客

交換後狀態| 2 | 6 | 4 | 1 | 5 | 9 |

 

第二次兩兩比較,6 > 4交換

交換前狀態| 2 | 6 | 4 | 1 | 5 | 9 |

交換後狀態| 2 | 4 | 6 | 1 | 5 | 9 |

 

第三次兩兩比較,6 > 1交換

交換前狀態| 2 | 4 | 6 | 1 | 5 | 9 |

交換後狀態| 2 | 4 | 1 | 6 | 5 | 9 |

 

第四次兩兩比較,6 > 5交換

交換前狀態| 2 | 4 | 1 | 6 | 5 | 9 |

交換後狀態| 2 | 4 | 1 | 5 | 6 | 9 |

 

第五次兩兩比較,6 < 9不交換

交換前狀態| 2 | 4 | 1 | 5 | 6 | 9 |

交換後狀態| 2 | 4 | 1 | 5 | 6 | 9 |

 

第二趟排序(外循環)

第一次兩兩比較2 < 4不交換

交換前狀態| 2 | 4 | 1 | 5 | 6 | 9 |

交換後狀態| 2 | 4 | 1 | 5 | 6 | 9 |

 

第二次兩兩比較,4 > 1交換

交換前狀態| 2 | 4 | 1 | 5 | 6 | 9 |  
交換後狀態| 2 | 1 | 4 | 5 | 6 | 9 |

 

第三次兩兩比較,4 < 5不交換

交換前狀態| 2 | 1 | 4 | 5 | 6 | 9 |  
交換後狀態| 2 | 1 | 4 | 5 | 6 | 9 |

 

第四次兩兩比較,5 < 6不交換

交換前狀態| 2 | 1 | 4 | 5 | 6 | 9 |

交換後狀態| 2 | 1 | 4 | 5 | 6 | 9 |

...

冒泡大概就這樣的流程

一開始跟着概念寫的(自我檢討,你們勿噴):

 1  private static String bubbleSort(int[] array) {
 2         int length = array.length;
 3         for (int i = 0; i < length; i++) {
 4             for (int j = 0; j < length; j++) {
 5 
 6                 if (j+1 >= length) {
 7                     break;
 8                 }
 9 
10                 int first = array[j];
11                 int second = array[j+1];
12                 if (first > second) {
13                     array[j] = second;
14                     array[j+1] = first;
15                 }
16             }
17         }
18         return Arrays.toString(array);
19     }
View Code

 

 

網上的:

 1 public class BubbleSort {
 2 
 3     public static void main(String[] args) {
 4 
 5         int[] array = new int[]{90, 12, 15, 15, 12, 90, 9, 21, 51, 3, 2, 1, 7, 8, 9};
 6         System.out.println("array:"+Arrays.toString(array));
 7         System.out.println("bubbleSort:"+bubbleSort(array));
 8     }
 9 
10     private static String bubbleSort(int[] array) {
11         int length = array.length;
12         for (int i = 0; i < length; i++) {
13             for (int j = 0; j < length-1-i; j++) {
14 
15                 int first = array[j];
16                 int second = array[j+1];
17                 if (first > second) {
18                     array[j] = second;
19                     array[j+1] = first;
20                 }
21             }
22         }
23         return Arrays.toString(array);
24     }
25 }
相關文章
相關標籤/搜索