氣泡排序是反覆進行將相鄰數字做比較後重新排序,因排序時一個一個浮出序列頂部,很像水中泡泡浮起來的樣子,亦稱泡泡排序,最壞情況下,數是由大排到小,每次比較後將數值對調,因此,時間複雜度為O(n^2)
。
Learn More →
圖片來源
function bubble_sort (array, length) {
var i, j;
for(i from 0 to length-1){
for(j from 0 to length-1-i){
if (array[j] > array[j+1])
swap(array[j], array[j+1])
}
}
}
給定一個數組 nums
,其中有 n
個對象,顏色為紅色、白色或藍色,並對它們進行排序,顏色按紅色、白色和藍色的順序排列。 將使用整數 0、1 和 2 分別表示紅色、白色和藍色。 必須在不使用library
的排序功能的情況下解決此問題。
Learn More →
使用泡泡排序解決此問題。
將陣列內數值由左至右雙雙比較,假設左邊數值大於右邊數值則互換位置,跑完一輪迴圈最右邊數值一定是最大的,進行第二圈比較時就可以省略比較最後一個數字,第三圈就忽略最後兩個數字,依此類推。
Javascript
/**
* @param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var sortColors = function(nums) {
for (let i=0; i < nums.length - 1; i++){
for (let j=0; j < nums.length - 1 - i; j++){
if (nums[j] > nums[j+1]) {
[nums[j], nums[j+1]] = [nums[j+1], nums[j]]
}
}
}
return nums;
};
@joe94113Tue, Oct 25, 2022 10:00 PM
最小生成樹(Minimum Spanning Tree,MST)是指在一個帶權無向圖中,找到一棵包含所有節點,權值最小的樹。其中,權值是指樹中所有邊權重的總和。
May 9, 2025運算式(Expression)有三種表示方式:中序式(Infix)、前序式(Prefix)、後序式(Postfix)
Dec 27, 2024Pinia簡介
Dec 26, 2024Object-Oriented Programming (OOP) Q1. What is an example of dynamic binding? [ ] any method [ ] method overloading [x] method overriding [ ] compiling Q2. For which case would the use of a static attribute be appropriate? [ ] the number of people in each house in a small neighborhood [ ] the lot size for each house in a small neighborhood
Dec 13, 2024or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up