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