国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁 web前端 js教程 了解冒泡排序算法:分步指南

了解冒泡排序算法:分步指南

Jan 02, 2025 pm 04:16 PM

Understanding Bubble Sort Algorithm: A Step-by-Step Guide

圖片來源:medium

排序是數(shù)據(jù)結(jié)構(gòu)和算法中最重要的部分之一。排序算法有很多種,這是最簡單的算法之一:冒泡排序。

排序算法是計算機科學(xué)的基礎(chǔ),而冒泡排序是最簡單、最直觀的排序算法之一。這篇文章將探討冒泡排序的工作原理,分析其時間復(fù)雜度,并演練 JavaScript 實現(xiàn)。

在本系列中,我將分享使用 Javascript 的完整排序算法數(shù)據(jù)結(jié)構(gòu)和算法,并從冒泡排序開始。如果您喜歡并希望我通過示例分享完整的排序算法,請喜歡并關(guān)注我。它激勵我為你們創(chuàng)建和準備內(nèi)容。

什么是冒泡排序?

冒泡排序是一種簡單的排序算法,它重復(fù)遍歷列表,比較相鄰元素(下一個元素),如果順序錯誤則交換它們。重復(fù)此過程直到列表排序完畢。該算法因其較小的元素“冒泡”到列表頂部而得名。

JavaScript 實現(xiàn):

讓我們深入代碼看看冒泡排序是如何在 JavaScript 中實現(xiàn)的:

// By default ascending order
function bubble_sort(array) {
    const len = array.length; // get the length of an array
    //The outer loop controls the inner loop, which means the outer loop will decide how many times the inner loop will be run.
    //If the length is n then the outer loop runs n-1 times.
    for (let i = 0; i < len - 1; i++) { 
        // Inner loop will run based on the outer loop and compare the value, 
        //If the first value is higher than the next value then swap it, loop must go on for each lowest value 
        for (let j = 0; j > len - i -1; j++) {
            // checking if the first element greater than to the next element
            if (array[j] > array[j + 1]) {
                // then, swap the value array[j] to array[j+1]
                let temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    return array; // return the sorted array;
}

const array =  [7, 12, 9, 11, 3]; // input data
console.log(bubble_sort(array));

// output data after sorted!
// [3, 7, 9, 11, 12]; 

輸出

Understanding Bubble Sort Algorithm: A Step-by-Step Guide

按降序排序:

// Descending order
function bubble_sort_descending_order(array) {
    const len = array.length;
    for (let i = 0; i < len - 1; i++) {
        for (let j = 0; j < len - i -1; j++) {
            // checking if first element greter than next element,
            if (array[j] < array[j + 1]) {
                // then, swap the value array[j] to array[j+1]
                let temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    return array;
}

const array =  [7, 12, 9, 11, 3]; // input data
console.log(bubble_sort_descending_order(array));

// output data after sorted!
// [ 12, 11, 9, 7, 3 ]

輸出:

Understanding Bubble Sort Algorithm: A Step-by-Step Guide

已經(jīng)添加了注釋并解釋了上面的每一行代碼。但我也會詳細解釋,以幫助您理解完整的流程和代碼。

工作原理:

  • 初始化:我們首先確定數(shù)組的長度,這有助于控制迭代次數(shù)。
  • 外循環(huán):該循環(huán)運行 n-1 次,其中 n 是數(shù)組的長度。每次迭代都會確保下一個最大元素被放置在正確的位置。
  • 內(nèi)循環(huán):對于外循環(huán)的每一次循環(huán),內(nèi)循環(huán)都會比較相鄰元素,如果它們無序,則交換它們。內(nèi)部循環(huán)的范圍隨著每次傳遞而減小,因為最大的元素已經(jīng)排序在數(shù)組的末尾。
  • 交換:如果一個元素大于下一個元素,則使用臨時變量交換它們。
  • 返回:最后返回排序后的數(shù)組。

優(yōu)化版本:

// By default ascending order
function bubble_sort(array) {
    const len = array.length; // get the length of an array
    //The outer loop controls the inner loop, which means the outer loop will decide how many times the inner loop will be run.
    //If the length is n then the outer loop runs n-1 times.
    for (let i = 0; i < len - 1; i++) { 
        // Inner loop will run based on the outer loop and compare the value, 
        //If the first value is higher than the next value then swap it, loop must go on for each lowest value 
        for (let j = 0; j > len - i -1; j++) {
            // checking if the first element greater than to the next element
            if (array[j] > array[j + 1]) {
                // then, swap the value array[j] to array[j+1]
                let temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    return array; // return the sorted array;
}

const array =  [7, 12, 9, 11, 3]; // input data
console.log(bubble_sort(array));

// output data after sorted!
// [3, 7, 9, 11, 12]; 

說明:

  • for (令 i = 0; i
  • 讓 isSwapped = false 布爾變量 isSwapped 被初始化為 false。該變量用于跟蹤在內(nèi)部循環(huán)的當前傳遞期間是否交換了任何元素。如果沒有發(fā)生交換,則數(shù)組已經(jīng)排序,算法可以提前終止。
  • for (令 j = 0; j
  • if (數(shù)組[j] > 數(shù)組[j 1]) { 此條件檢查當前元素是否大于下一個元素。如果為 true,則需要進行交換才能正確排序元素。
// Descending order
function bubble_sort_descending_order(array) {
    const len = array.length;
    for (let i = 0; i < len - 1; i++) {
        for (let j = 0; j < len - i -1; j++) {
            // checking if first element greter than next element,
            if (array[j] < array[j + 1]) {
                // then, swap the value array[j] to array[j+1]
                let temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
            }
        }
    }

    return array;
}

const array =  [7, 12, 9, 11, 3]; // input data
console.log(bubble_sort_descending_order(array));

// output data after sorted!
// [ 12, 11, 9, 7, 3 ]
  • 這些行使用臨時變量 temp 執(zhí)行元素 array[j] 和 array[j 1] 的交換。交換后,isSwapped 設(shè)置為 true,表示發(fā)生了交換。
// optimized version:
function bubble_sort(array) {
    const len = array.length; // get the length of the array
    //The outer loop controls the inner loop, which means the outer loop will decide how many times the inner loop will be run.
    //If the length is n then the outer loop run n-1 times.
    for (let i = 0; i < len - 1; i++) { 
        // Inner loop will run based on the outer loop and compare the value, 
        //If the first value is higher than the next value then swap it, loop must go on for each lowest value
        let isSwapped = false;
        for (let j = 0; j < len - i -1; j++) {
            //check if the first element is greater than the next element
            if (array[j] > array[j + 1]) {
                // then, swap the value array[j] to array[j+1]
                let temp = array[j];
                array[j] = array[j + 1];
                array[j + 1] = temp;
                isSwapped =  true;
            }
        }

        //If no element swap by inner loop then break;
        if (isSwapped === false) {
            break;
        }
    }

    return array;
}

const array =  [7, 12, 9, 11, 3]; // input data
console.log(bubble_sort(array));

// output data after sorted!
// [3, 7, 9, 11, 12]; 

  • 內(nèi)部循環(huán)完成后,此條件檢查 isSwapped 是否仍然為 false。如果沒有進行交換,則數(shù)組已經(jīng)排序,并且可以使用break提前退出外循環(huán)。
  • 最后返回排序后的數(shù)組。

時間復(fù)雜度

在最壞和平均情況下,冒泡排序的時間復(fù)雜度為 (O(n2)),其中 (n) 是數(shù)組中元素的數(shù)量。這是因為每個元素都會與其他元素進行比較。在最好的情況下,當數(shù)組已經(jīng)排序時,如果添加優(yōu)化以在不需要交換時停止算法,時間復(fù)雜度可以是 (O(n))。

在最好的情況下,當數(shù)組已經(jīng)排序時,由于 isSwapped 優(yōu)化,算法可以提前終止,導(dǎo)致時間復(fù)雜度為 (O(n))。

總體而言,由于其二次時間復(fù)雜度,冒泡排序?qū)τ诖笮蛿?shù)據(jù)集效率不高,但它對于小型數(shù)組很有用,或者作為理解排序算法的教育工具。

結(jié)論

冒泡排序由于其簡單性而成為一種用于教育目的的優(yōu)秀算法。然而,由于其二次時間復(fù)雜度,它不適合大型數(shù)據(jù)集。盡管冒泡排序效率低下,但理解冒泡排序為學(xué)習更高級的排序算法奠定了基礎(chǔ)。

以上是了解冒泡排序算法:分步指南的詳細內(nèi)容。更多信息請關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻,版權(quán)歸原作者所有,本站不承擔相應(yīng)法律責任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣服圖片

Undresser.AI Undress

Undresser.AI Undress

人工智能驅(qū)動的應(yīng)用程序,用于創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用于從照片中去除衣服的在線人工智能工具。

Clothoff.io

Clothoff.io

AI脫衣機

Video Face Swap

Video Face Swap

使用我們完全免費的人工智能換臉工具輕松在任何視頻中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的代碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

功能強大的PHP集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級代碼編輯軟件(SublimeText3)

Java vs. JavaScript:清除混亂 Java vs. JavaScript:清除混亂 Jun 20, 2025 am 12:27 AM

Java和JavaScript是不同的編程語言,各自適用于不同的應(yīng)用場景。Java用于大型企業(yè)和移動應(yīng)用開發(fā),而JavaScript主要用于網(wǎng)頁開發(fā)。

JavaScript評論:簡短說明 JavaScript評論:簡短說明 Jun 19, 2025 am 12:40 AM

JavascriptconcommentsenceenceEncorenceEnterential gransimenting,reading and guidingCodeeXecution.1)單inecommentsareusedforquickexplanations.2)多l(xiāng)inecommentsexplaincomplexlogicorprovideDocumentation.3)

如何在JS中與日期和時間合作? 如何在JS中與日期和時間合作? Jul 01, 2025 am 01:27 AM

JavaScript中的日期和時間處理需注意以下幾點:1.創(chuàng)建Date對象有多種方式,推薦使用ISO格式字符串以保證兼容性;2.獲取和設(shè)置時間信息可用get和set方法,注意月份從0開始;3.手動格式化日期需拼接字符串,也可使用第三方庫;4.處理時區(qū)問題建議使用支持時區(qū)的庫,如Luxon。掌握這些要點能有效避免常見錯誤。

為什么要將標簽放在的底部? 為什么要將標簽放在的底部? Jul 02, 2025 am 01:22 AM

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScript與Java:開發(fā)人員的全面比較 JavaScript與Java:開發(fā)人員的全面比較 Jun 20, 2025 am 12:21 AM

JavaScriptIspreferredforredforwebdevelverment,而Javaisbetterforlarge-ScalebackendsystystemsandSandAndRoidApps.1)JavascriptexcelcelsincreatingInteractiveWebexperienceswebexperienceswithitswithitsdynamicnnamicnnamicnnamicnnamicnemicnemicnemicnemicnemicnemicnemicnemicnddommanipulation.2)

JavaScript:探索用于高效編碼的數(shù)據(jù)類型 JavaScript:探索用于高效編碼的數(shù)據(jù)類型 Jun 20, 2025 am 12:46 AM

javascripthassevenfundaMentalDatatypes:數(shù)字,弦,布爾值,未定義,null,object和symbol.1)numberSeadUble-eaduble-ecisionFormat,forwidevaluerangesbutbecautious.2)

什么是在DOM中冒泡和捕獲的事件? 什么是在DOM中冒泡和捕獲的事件? Jul 02, 2025 am 01:19 AM

事件捕獲和冒泡是DOM中事件傳播的兩個階段,捕獲是從頂層向下到目標元素,冒泡是從目標元素向上傳播到頂層。1.事件捕獲通過addEventListener的useCapture參數(shù)設(shè)為true實現(xiàn);2.事件冒泡是默認行為,useCapture設(shè)為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委托,提高動態(tài)內(nèi)容處理效率;5.捕獲可用于提前攔截事件,如日志記錄或錯誤處理。了解這兩個階段有助于精確控制JavaScript響應(yīng)用戶操作的時機和方式。

Java和JavaScript有什么區(qū)別? Java和JavaScript有什么區(qū)別? Jun 17, 2025 am 09:17 AM

Java和JavaScript是不同的編程語言。1.Java是靜態(tài)類型、編譯型語言,適用于企業(yè)應(yīng)用和大型系統(tǒng)。2.JavaScript是動態(tài)類型、解釋型語言,主要用于網(wǎng)頁交互和前端開發(fā)。

See all articles