LeetCode
sort
selection sort
Learn More →
Learn More →
( 圖片來源 wiki )
邏輯:
arr <- an unsorted array of integers
let len be the length of arr
for i (0 to len-1) do
let minIndex = i
for j (i+1 to len-1) do
if (arr[j] < arr[minIndex]) then
minIndex = j
end if
end for
swap(arr, i, minIndex)
end for
func swap(arr, firstIndex, minIndex):
temp = arr[firstIndex]
arr[firstIndex] = arr[minIndex]
arr[minIndex] = temp
end func
程式碼實作:
debugger
function swap(arr, firstIndex, minIndex) {
temp = arr[firstIndex]
arr[firstIndex] = arr[minIndex]
arr[minIndex] = temp
}
function selectionSort(arr) {
for (let i = 0; i < arr.length; i++) {
let minIndex = i
for (j=i+1 ; j<arr.length ; j++) {
minIndex = (arr[j]<arr[minIndex]) ? j : minIndex
}
swap(arr, i, minIndex)
console.log(arr)
}
}
selectionSort([8, 9, 2, 5, 1])
題目連結 一、理解題目 二、Edge Case 是否有極限值或特殊情況 三、題目思考 使用哪種資料結構: 步驟
Nov 27, 2023Introduction 簡介 Sorting / Searching Insertion Sort Selection Sort Bubble Sort Merge Sort
Oct 13, 2021:::info :pushpin: 二元搜尋法,也就是將排序好的資料分割成兩等份。每次挑出一個數字,和中間值比較,判斷目標在前半或後半。然後再進行二元分割。它的時間複雜度是 $O(log n)$。 ::: {%youtube T2sFYY-fT5o %} 一、步驟觀察 找出中間值 如果目標值 === 中間值,則傳回 index 如果目標值 > 中間值,則從右邊子陣列找,重複步驟一 (recur for the right half)
Oct 13, 2021:::info :pushpin: 合併排序法採用了分治法 ( Divide and Conquer ) 概念,將陣列對半拆開,拆到小陣列只剩一個元素,拆開之後,排序再合併。它的時間複雜度是 $O(nlogn)$。 ::: {%youtube JSceec-wEyw %} 一、步驟觀察 將陣列對半拆分至剩一個元素 ( Divide,並使用到 ==Recursive 的概念== ) 針對相鄰兩個陣列做完比較後,完成排序與合併 ( Conquer )
Oct 6, 2021or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up