<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          十大排序之冒泡排序

          共 1463字,需瀏覽 3分鐘

           ·

          2021-04-18 05:49

          十大排序之冒泡排序(BubbleSort)


          01

          4.15

          簡(jiǎn)介

              冒泡排序是一種很經(jīng)典的算法,它的思路也很簡(jiǎn)單:

          比較相鄰的元素。如果第一個(gè)比第二個(gè)大,就交換他們兩個(gè)。

          對(duì)每一對(duì)相鄰元素作同樣的工作,從開始第一對(duì)到結(jié)尾的最后一對(duì)。這步做完后,最后的元素會(huì)是最大的數(shù)。

          針對(duì)所有的元素重復(fù)以上的步驟,除了最后一個(gè)。

          持續(xù)每次對(duì)越來越少的元素重復(fù)上面的步驟,直到?jīng)]有任何一對(duì)數(shù)字需要比較。


          冒泡排序的時(shí)間復(fù)雜度是:O(n2) , 空間復(fù)雜度是:O(1) 



          02

          4.15

          圖解流程

           

            假設(shè)我們待排序數(shù)組是:5  4   7  1   2  3

            首先開始進(jìn)行第一輪排序,第一個(gè)數(shù)和第二個(gè)數(shù)比較,第二個(gè)和第三個(gè)比較,。。。。。

            第一輪比較之后,最大的數(shù)會(huì)到最后一位。

            重復(fù)上述步驟,知道完成排序。






          03

          4.15

          代碼實(shí)現(xiàn)

          package com.znzz.bubblesort;
          import java.util.Arrays;
          public class BubbleSort {
          public static void main(String[] args) { int[] arr = {4,5,7,3,1,2}; bubbleSort(arr); } public static void bubbleSort(int[] arr){ int swapCount = 0; //交換輪數(shù) boolean swaped = false; //假設(shè)沒有元素交換 for (int i = 0; i < arr.length-1; i++) { for (int j = 0; j < arr.length - i -1; j++) { if(arr[j] > arr[j+1]){ int temp; temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swaped = true; swapCount++; }
          } if(!swaped){ break; } } System.out.println(Arrays.toString(arr)); System.out.println("交換的次數(shù):"+swapCount); }}






          如果該文章對(duì)你有幫助,"再看"和"點(diǎn)贊"是對(duì)我最大的鼓勵(lì)!

          掃二維碼|關(guān)注我們




          謝謝觀看


          把城市夜晚的喧囂,點(diǎn)出來


          瀏覽 46
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  www.日韩AV | 大香蕉网伊 | 青青久久 | 久久好色 | 国产精品偷窥熟女精品视 |