Different Sort
Bubble/Selection/Quick
Count ζζ― 15 欑
function getSort(){
let initArr = [8, 9, 2, 5, 1]
let checkLen = initArr.length - 1
function bubbleSort(arr, checkLen){
// θ¨ recursion ηεζι»
if(checkLen <= 0) return
for(let i = 0; i< checkLen; i++){
// θ₯ε·¦ιζ―ε³ι倧ι£ε°±δΊ€ζ
if(arr[i] > arr[i+1]){
[arr[i], arr[i+1]] = [arr[i+1], arr[i]]
}
count++
}
bubbleSort(arr, checkLen-1)
return arr
}
let result = bubbleSort(initArr, checkLen)
return result
}
getSort()
Selection Sort
function selectionSort(arr, startIndex){
// θ¨ recursion ηεζι»
if(startIndex > arr.length - 1) return
let minIndex = startIndex;
for(let i = startIndex; i< arr.length; i++){
if(arr[i] < arr[minIndex]){
minIndex = i
}
}
// ζΎε°ζε°ι£εθ· startIndex δΊ€ζ
[arr[startIndex], arr[minIndex]] = [arr[minIndex], arr[startIndex]]
selectionSort(arr, startIndex+1)
return arr
}
Qick Sort
function quickSort(arr) {
if (arr.length < 2) return arr
const [p, ...ary] = arr
const left = [], right = []
ary.forEach(c => {
if (c < p) left.push(c)
else right.push(c)
})
return [...quickSort(left), p, ...quickSort(right)]
}
Last updated