冒泡排序算法思想:

讓數組中的兩個相鄰數字進行比較,數組中較大的值向下沉,值小的上浮,就類似於水中的氣泡,較大的下沉,較小的上升,慢慢冒出來。簡單的說就是數值大的會慢慢往前排,數據值小的會慢慢向後排,最終實現由小到達排列,最小的排在最前,最大的排到最後。

冒泡排序圖解:

算法執行前

算法執行後

冒泡排序算法JAVA實現代碼

import com.jiajia.ArrayUtil.*; // 按包名導入

public class BubbleSortMain {

public static void main(String[] args) {

int[] arr = {3,43,38,5,47,15,36,26,27,2,44,4,50,19,38};

bubbleSort(arr);

ArrayUtil.print(arr);

}

/**

* 冒泡排序

*/

private static void bubbleSort(int[] arr) {

for (int i = 0; i < arr.length; i++) {

for (int j = 0; j < arr.length - i -1; j++) { // 這裏說明爲什麼需要-1

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

}

}

}

}

}

冒泡排序算法python實現代碼

def bubble_sort(the_list):

i = 0

while i < len(the_list):

j = 0

while j < len(the_list)-1:

print(the_list[j],the_list[j+1])

if the_list[j] > the_list[j+1]:

the_list[j], the_list[j+1] = the_list[j+1], the_list[j]

j = j+1

print(the_list)

print("======"+str(the_list))

i = i+1

return the_list

if __name__ == '__main__':

the_list = [3, 43, 38, 5, 47, 15, 36, 26, 27, 2, 44, 4, 50, 19, 38]

print("排序前:" + str(the_list))

print("排序後:" + str(bubble_sort(the_list)))

相關文章