iT邦幫忙

2022 iThome 鐵人賽

DAY 3
0
自我挑戰組

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

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

  • 分享至 

  • xImage
  •  

Insertion Sort
Traversal in Binary Tree:

將下一順位(j = i + 1)的陣列數值與當前(i)、過去(j--)的陣列數值進行大小比對,
符合則交換位置。

https://ithelp.ithome.com.tw/upload/images/20220903/20152092H7n8S12bNM.png

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

let insertionSort = (nums) => {
  let length = nums.length;

  for (let i = 1; i < length; i++) {
    let current = nums[i];
    let j = i - 1;

    //如果 nums[i] 小於之前的元素,則進行交換。
    while ((j > -1) && (current < nums[j])) {
      nums[j + 1] = nums[j];
      j--;
    }
    nums[j + 1] = current;
  }
  return nums;
}

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

Flow Chart:

[ 1, 2, 3, 2, 1, 6 ]
[ 1, 2, 3, 2, 1, 6 ]
[ 1, 2, 2, 3, 1, 6 ]
[ 1, 1, 2, 2, 3, 6 ]
[ 1, 1, 2, 2, 3, 6 ]
[ 1, 1, 2, 2, 3, 6 ]

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


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

尚未有邦友留言

立即登入留言