国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

冒泡排序和選擇排序

2019-11-06 06:20:13
字體:
供稿:網(wǎng)友

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 bubbleSort

代碼實(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

select sort

代碼實(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中,故不做分析。。。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 普定县| 巴东县| 平乡县| 曲阳县| 弥勒县| 邛崃市| 静宁县| 禄丰县| 武威市| 土默特右旗| 新河县| 封开县| 旺苍县| 保康县| 耒阳市| 永泰县| 许昌市| 阿瓦提县| 开封市| 长宁区| 铜川市| 白山市| 上林县| 邵阳县| 德州市| 龙门县| 佳木斯市| 潢川县| 南和县| 沾益县| 芦山县| 金溪县| 正定县| 青铜峡市| 乐至县| 额敏县| 新晃| 固原市| 建水县| 资溪县| 宜兰市|