---
description: Bubble/Selection/Quick
---

# Different Sort

Count 會是 15 次

```javascript
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



```javascript
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

```javascript
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)]
}
```
