Bubble sort:
sometimes referred to as sinking sort, is a simple sorting algorithmthat repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. (from WIKI)
每相鄰的兩個(gè)數(shù)比較,大的下沉,小的上浮
Ps: 假設(shè)有這樣一個(gè)數(shù)組 int[] a = { a1,a2,a3,a4,a5,a6};
1 a[0]與a[1] a[1]與a[2] a[2]與a[3] a[3]與a[4] a[4]與a[5] 得到a[5]
2 a[0]與a[1] a[1]與a[2] a[2]與a[3] a[3]與a[4] 得到a[4]
3 a[0]與a[1] a[1]與a[2] a[2]與a[3] 得到a[3]
4 a[0]與a[1] a[1]與a[2] 得到a[2]
5 a[0]與a[1] 得到a[1] over
典型的for循環(huán)嵌套,一個(gè)控制行(比較的次數(shù)),一個(gè)控制列數(shù)(每次比較需要循環(huán)的次數(shù))。為了更直觀,貼圖一張:By Swfung8-Own work, bubble  sort GIF 
代碼實(shí)現(xiàn):
public static void bubbleSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = 0; j < arr.length - 1 - i; j++) { if (arr[j] > arr[j + 1]) { swap(arr,j,j+1); } } } }Swap方法:
PRivate static void swap(int[] arr,int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }Select Sort:
The algorithm divides the input list into two parts: the sublist of items already sorted, which is built up from left to right at the front (left) of the list, and the sublist of items remaining to be sorted that occupy the rest of the list. Initially, the sorted sublist is empty and the unsorted sublist is the entire input list. The algorithm proceeds by finding the smallest (or largest, depending on sorting order) element in the unsorted sublist, exchanging (swapping) it with the leftmost unsorted element (putting it in sorted order), and moving the sublist boundaries one element to the right.(from WIKI)
64 25 12 22 11 // this is the initial, starting state of the array11 25 12 22 64 // sorted sublist = {11}11 12 25 22 64 // sorted sublist = {11, 12}11 12 22 25 64 // sorted sublist = {11, 12, 22}11 12 22 25 64 // sorted sublist = {11, 12, 22, 25}11 12 22 25 64 // sorted sublist = {11, 12, 22, 25, 64}簡單來說:
先從數(shù)組中找出最小的排列在左側(cè)的sorted sublist,然后在剩下的unsorted element里找出最小的元素添加到左側(cè)的sorted sublist,好比蛇通象最終形成一個(gè)有序的數(shù)組。
為了更直觀,貼圖一張,By Joestape89 at the English language Wikipedia, CC BY-SA 3.0, select sort GIF

代碼實(shí)現(xiàn):
private static void selectSort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { for (int j = i + 1; j < arr.length; j++) { if (arr[i] > arr[j]) { swap(arr,i,j); } } } }牽涉到算法的具體分析方面,本人還在fighting中,故不做分析。。。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注