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

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

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

Jan 02, 2025 pm 04:16 PM

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

圖片來源:medium

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

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

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

什麼是冒泡排序?

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

JavaScript 實作:

讓我們深入程式碼看看冒泡排序是如何在 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

已經加入了註解並解釋了上面的每一行程式碼。但我也會詳細解釋,以幫助您理解完整的流程和程式碼。

工作原理:

  • 初始化:我們先確定陣列的長度,這有助於控制迭代次數(shù)。
  • 外循環(huán):此循環(huán)運行 n-1 次,其中 n 是陣列的長度。每次迭代都會確保下一個最大元素被放置在正確的位置。
  • 內循環(huán):對於外循環(huán)的每一次循環(huán),內循環(huán)都會比較相鄰元素,如果它們無序,則交換它們。內部循環(huán)的範圍隨著每次傳遞而減小,因為最大的元素已經排序在陣列的??末端。
  • 交換:如果一個元素大於下一個元素,則使用臨時變數(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 (設 i = 0; i
  • 讓 isSwapped = false 布林變數(shù) isSwapped 被初始化為 false。此變數(shù)用於追蹤在內部循環(huán)的當前傳遞期間是否交換了任何元素。如果沒有發(fā)生交換,則陣列已經排序,演算法可以提前終止。
  • 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 ]
  • 這些行使用臨時變數(shù) temp 執(zhí)行元素 array[j] 和 array[j 1] 的交換。交換後,isSwapped 設定為 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]; 

  • 內部迴圈完成後,此條件檢查 isSwapped 是否仍為 false。如果沒有進行交換,則陣列已經排序,並且可以使用break提前退出外部循環(huán)。
  • 最後傳回排序後的陣列。

時間複雜度

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

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

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

結論

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

以上是了解冒泡排序演算法:逐步指南的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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

熱AI工具

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創(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

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

SublimeText3 Mac版

SublimeText3 Mac版

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

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

Java和JavaScript是不同的編程語言,各自適用於不同的應用場景。 Java用於大型企業(yè)和移動應用開發(fā),而JavaScript主要用於網頁開發(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.獲取和設置時間信息可用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ù)據類型 JavaScript:探索用於高效編碼的數(shù)據類型 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ù)設為true實現(xiàn);2.事件冒泡是默認行為,useCapture設為false或省略;3.可使用event.stopPropagation()阻止事件傳播;4.冒泡支持事件委託,提高動態(tài)內容處理效率;5.捕獲可用於提前攔截事件,如日誌記錄或錯誤處理。了解這兩個階段有助於精確控制JavaScript響應用戶操作的時機和方式。

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

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

See all articles