|
1 |
| -/* In insertion sort, we divide the initial unsorted array into two parts; |
2 |
| -* sorted part and unsorted part. Initially the sorted part just has one |
3 |
| -* element (Array of only 1 element is a sorted array). We then pick up |
4 |
| -* element one by one from unsorted part; insert into the sorted part at |
5 |
| -* the correct position and expand sorted part one element at a time. |
| 1 | +/** |
| 2 | + * @function InsertionSort |
| 3 | + * @description Quick sort is a stable sorting algorithm |
| 4 | + * @param {Integer[]} array - Array of integers |
| 5 | + * @return {Integer[]} - Sorted array |
| 6 | + * @see [InsertionSort](https://en.wikipedia.org/wiki/Quicksort) |
| 7 | + */ |
| 8 | + |
| 9 | +/* |
| 10 | + * Big-O Analysis |
| 11 | + * Time Complexity |
| 12 | + - O(N^2) on average and worst case scenario |
| 13 | + - O(N) on best case scenario (when input array is already almost sorted) |
| 14 | + * Space Complexity |
| 15 | + - O(1) |
6 | 16 | */
|
7 |
| -export function insertionSort (unsortedList) { |
8 |
| - const len = unsortedList.length |
9 |
| - for (let i = 1; i < len; i++) { |
10 |
| - let j |
11 |
| - const tmp = unsortedList[i] // Copy of the current element. |
12 |
| - /* Check through the sorted part and compare with the number in tmp. If large, shift the number */ |
13 |
| - for (j = i - 1; j >= 0 && (unsortedList[j] > tmp); j--) { |
14 |
| - // Shift the number |
15 |
| - unsortedList[j + 1] = unsortedList[j] |
| 17 | + |
| 18 | +/* In insertion sort, we divide the initial unsorted array into two parts; |
| 19 | + * sorted part and unsorted part. Initially the sorted part just has one |
| 20 | + * element (Array of only 1 element is a sorted array). We then pick up |
| 21 | + * element one by one from unsorted part; insert into the sorted part at |
| 22 | + * the correct position and expand sorted part one element at a time. |
| 23 | + */ |
| 24 | + |
| 25 | +export function insertionSort (array) { |
| 26 | + const length = array.length |
| 27 | + if (length < 2) return array |
| 28 | + |
| 29 | + for (let i = 1; i < length; i++) { |
| 30 | + // Take current element in array |
| 31 | + const currentItem = array[i] |
| 32 | + // Take index of previous element in array |
| 33 | + let j = i - 1 |
| 34 | + |
| 35 | + // While j >= 0 and previous element is greater than current element |
| 36 | + while (j >= 0 && array[j] > currentItem) { |
| 37 | + // Move previous, greater element towards the unsorted part |
| 38 | + array[j + 1] = array[j] |
| 39 | + j-- |
16 | 40 | }
|
17 |
| - // Insert the copied number at the correct position |
18 |
| - // in sorted part. |
19 |
| - unsortedList[j + 1] = tmp |
| 41 | + // Insert currentItem number at the correct position in sorted part. |
| 42 | + array[j + 1] = currentItem |
20 | 43 | }
|
| 44 | + return array |
21 | 45 | }
|
0 commit comments