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

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

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

Jan 02, 2025 pm 04:16 PM

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

圖片來源:medium

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

排序演算法是電腦科學(xué)的基礎(chǔ),而冒泡排序是最簡單、最直觀的排序演算法之一。這篇文章將探討冒泡排序的工作原理,分析其時(shí)間複雜度,並演練 JavaScript 實(shí)作。

在本系列中,我將分享使用 Javascript 的完整排序演算法資料結(jié)構(gòu)和演算法,並從冒泡排序開始。如果您喜歡並希望我透過範(fàn)例分享完整的排序演算法,請按讚並關(guān)注我。它激勵(lì)我為你們創(chuàng)作和準(zhǔn)備內(nèi)容。

什麼是冒泡排序?

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

JavaScript 實(shí)作:

讓我們深入程式碼看看冒泡排序是如何在 JavaScript 中實(shí)現(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)加入了註解並解釋了上面的每一行程式碼。但我也會(huì)詳細(xì)解釋,以幫助您理解完整的流程和程式碼。

工作原理:

  • 初始化:我們先確定陣列的長度,這有助於控制迭代次數(shù)。
  • 外循環(huán):此循環(huán)運(yùn)行 n-1 次,其中 n 是陣列的長度。每次迭代都會(huì)確保下一個(gè)最大元素被放置在正確的位置。
  • 內(nèi)循環(huán):對於外循環(huán)的每一次循環(huán),內(nèi)循環(huán)都會(huì)比較相鄰元素,如果它們無序,則交換它們。內(nèi)部循環(huán)的範(fàn)圍隨著每次傳遞而減小,因?yàn)樽畲蟮脑匾呀?jīng)排序在陣列的??末端。
  • 交換:如果一個(gè)元素大於下一個(gè)元素,則使用臨時(shí)變數(shù)交換它們。
  • 傳回:最後傳回排序後的陣列。

最佳化版本:

// 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 (設(shè) i = 0; i
  • 讓 isSwapped = false 布林變數(shù) isSwapped 被初始化為 false。此變數(shù)用於追蹤在內(nèi)部循環(huán)的當(dāng)前傳遞期間是否交換了任何元素。如果沒有發(fā)生交換,則陣列已經(jīng)排序,演算法可以提前終止。
  • for (設(shè) j = 0; j
  • if (數(shù)組[j] > 數(shù)組[j 1]) { 此條件檢查目前元素是否大於下一個(gè)元素。如果為 true,則需要進(jìn)行交換才能正確排序元素。
// 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 ]
  • 這些行使用臨時(shí)變數(shù) 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)部迴圈完成後,此條件檢查 isSwapped 是否仍為 false。如果沒有進(jìn)行交換,則陣列已經(jīng)排序,並且可以使用break提前退出外部循環(huán)。
  • 最後傳回排序後的陣列。

時(shí)間複雜度

在最壞和平均情況下,冒泡排序的時(shí)間複雜度為 (O(n2)),其中 (n) 是數(shù)組中元素的數(shù)量。這是因?yàn)槊總€(gè)元素都會(huì)與其他元素進(jìn)行比較。在最好的情況下,當(dāng)數(shù)組已經(jīng)排序時(shí),如果添加最佳化以在不需要交換時(shí)停止演算法,則時(shí)間複雜度可以是 (O(n))。

在最好的情況下,當(dāng)陣列已經(jīng)排序時(shí),由於 isSwapped 最佳化,演算法可以提前終止,導(dǎo)致時(shí)間複雜度為 (O(n))。

整體而言,由於其二次時(shí)間複雜度,冒泡排序?qū)洞笮唾Y料集效率不高,但它對於小型數(shù)組很有用,或者作為理解排序演算法的教育工具。

結(jié)論

冒泡排序因其簡單性而成為一種用於教育目的的優(yōu)秀演算法。然而,由於其二次時(shí)間複雜度,它不適合大型資料集。儘管冒泡排序效率低下,但理解冒泡排序?yàn)閷W(xué)習(xí)更高級(jí)的排序演算法奠定了基礎(chǔ)。

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

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

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

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

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

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

JavaScript評(píng)論:簡短說明 JavaScript評(píng)論:簡短說明 Jun 19, 2025 am 12:40 AM

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

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

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

為什麼要將標(biāo)籤放在的底部? 為什麼要將標(biāo)籤放在的底部? 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中事件傳播的兩個(gè)階段,捕獲是從頂層向下到目標(biāo)元素,冒泡是從目標(biāo)元素向上傳播到頂層。 1.事件捕獲通過addEventListener的useCapture參數(shù)設(shè)為true實(shí)現(xiàn);2.事件冒泡是默認(rèn)行為,useCapture設(shè)為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委託,提高動(dòng)態(tài)內(nèi)容處理效率;5.捕獲可用於提前攔截事件,如日誌記錄或錯(cuò)誤處理。了解這兩個(gè)階段有助於精確控制JavaScript響應(yīng)用戶操作的時(shí)機(jī)和方式。

如何減少JavaScript應(yīng)用程序的有效載荷大??? 如何減少JavaScript應(yīng)用程序的有效載荷大??? Jun 26, 2025 am 12:54 AM

如果JavaScript應(yīng)用加載慢、性能差,問題往往出在payload太大,解決方法包括:1.使用代碼拆分(CodeSplitting),通過React.lazy()或構(gòu)建工具將大bundle拆分為多個(gè)小文件,按需加載以減少首次下載量;2.移除未使用的代碼(TreeShaking),利用ES6模塊機(jī)制清除“死代碼”,確保引入的庫支持該特性;3.壓縮和合併資源文件,啟用Gzip/Brotli和Terser壓縮JS,合理合併文件並優(yōu)化靜態(tài)資源;4.替換重型依賴,選用輕量級(jí)庫如day.js、fetch

See all articles