Insertion Sort
Traversal in Binary Tree:
將下一順位(j = i + 1)的陣列數值與當前(i)、過去(j--)的陣列數值進行大小比對, 符合則交換位置。
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 ]