首頁(yè)技術(shù)文章正文

冒泡排序法|java、python冒泡排序?qū)崿F(xiàn)代碼

更新時(shí)間:2019-11-20 來(lái)源:黑馬程序員 瀏覽量:

冒泡排序算法思想:

讓數(shù)組中的兩個(gè)相鄰數(shù)字進(jìn)行比較,數(shù)組中較大的值向下沉,值小的上浮,就類似于水中的氣泡,較大的下沉,較小的上升,慢慢冒出來(lái)。簡(jiǎn)單的說(shuō)就是數(shù)值大的會(huì)慢慢往前排,數(shù)據(jù)值小的會(huì)慢慢向后排,最終實(shí)現(xiàn)由小到達(dá)排列,最小的排在最前,最大的排到最后。

冒泡排序圖解:

1574231046597_冒泡排序算法執(zhí)行前開始前.jpg

算法執(zhí)行前






1574674127104_冒泡排序算法執(zhí)行后.jpg

算法執(zhí)行后





1574231078139_冒泡排序動(dòng)圖.gif

冒泡算法執(zhí)行過程【動(dòng)圖版】


冒泡排序算法JAVA實(shí)現(xiàn)代碼

import com.jiajia.ArrayUtil.*;  // 按包名導(dǎo)入


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++) {   // 這里說(shuō)明為什么需要-1

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

                    int temp = arr[j];

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

                    arr[j + 1] = temp;

                }

            }

        }

    }

}


冒泡排序算法python實(shí)現(xiàn)代碼


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)))

原文:冒泡排序算法

分享到:

Java培訓(xùn)班課程javaee

Python培訓(xùn)機(jī)構(gòu)python大數(shù)據(jù)

web前端培訓(xùn)課程升級(jí)V8.5web

AI+設(shè)計(jì)培訓(xùn)課程ui

大數(shù)據(jù)培訓(xùn)課程cloud

軟件測(cè)試培訓(xùn)課程test

c

新媒體運(yùn)營(yíng)培訓(xùn)netmarket

產(chǎn)品經(jīng)理培訓(xùn)課程pm

linux培訓(xùn)Linux

movies

智能機(jī)器人培訓(xùn)robot

電商視覺設(shè)計(jì)課程uids

AI

集成電路應(yīng)用開發(fā)(嵌入式)培訓(xùn)課程jdbc

在線咨詢 我要報(bào)名
和我們?cè)诰€交談!