iT邦幫忙

2022 iThome 鐵人賽

DAY 6
0
自我挑戰組

JavaScript - 30天 - 自學挑戰系列 第 6

關於Quick Sort排序方法與示意圖

  • 分享至 

  • xImage
  •  

Quick Sort
Traversal in Binary Tree:

快速排序是選擇一個數值作為基準(基準值:pivot),並將剩下的數值與基準進行大於、小於的群組分類,並在運算的過程中完成升降冪排序。

ex.Input : nums = [3, 2, 1]
           pivot =       V

                      #
step.1     nums    = [3, 2]
           pivot   =     1
           newNums = [1 , 3]

                      #
step.2     nums    = [2]
           pivot   =     1
           newNums = [1, 2, 3]

https://ithelp.ithome.com.tw/upload/images/20220908/20152092z5n3WbfAV2.png

Input: nums = [1, 2, 3, 2, 1, 6]

let quickSort = (nums) => {
  if (nums.length <= 1) return nums

  let pivot = nums[nums.length - 1]
  let left = [], right = []
  let i = 0
  
  while (i < nums.length - 1)  {
    if (nums[i] < pivot) {
      left.push(nums[i])
    } else {
      right.push(nums[i])
    }
  i++
  }
  return quickSort(left).concat(pivot, quickSort(right))
}

console.log(quickSort([1, 2, 3, 2, 1, 6]))

Output: newNums = [1, 1, 2, 2, 3, 6]

Flow Chart:

Input: nums = [1, 2, 3, 2, 1, 6]

console.log(pivot, left, right)

6, [ 1, 2, 3, 2, 1 ], [] //[6]
1, [], [ 1, 2, 3, 2 ]    //[1, ... ,6]
2, [ 1 ], [ 2, 3 ]       //[1, 1, 2, ... ,6]  
3, [ 2 ], []             //[1, 1, 2, 2, 3 ,6]  

Output: nums = [ 1, 1, 2, 2, 3, 6 ]

.concat(a, b):

var num1 = [1, 2, 3],
    num2 = [4, 5, 6],
    num3 = [7, 8, 9];

var nums = num1.concat(num2, num3);

console.log(nums);
//Output:[1, 2, 3, 4, 5, 6, 7, 8, 9]

Blog:http://52.198.119.162/關於quick-sort排序方法與示意圖/


上一篇
關於Merge Sort排序方法與示意圖
下一篇
關於Linear Search搜尋方法與示意圖
系列文
JavaScript - 30天 - 自學挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言