11/* 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.
6- */
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.
6+ */
7+
78export function insertionSort (unsortedList) {
89 const len = unsortedList.length
910 for (let i = 1; i < len; i++) {
@@ -19,3 +20,43 @@ export function insertionSort (unsortedList) {
1920 unsortedList[j + 1] = tmp
2021 }
2122}
23+
24+ /**
25+ * @function insertionSortAlternativeImplementation
26+ * @description InsertionSort is a stable sorting algorithm
27+ * @param {Integer[]} array - Array of integers
28+ * @return {Integer[]} - Sorted array
29+ * @see [InsertionSort](https://en.wikipedia.org/wiki/Quicksort)
30+ */
31+
32+ /*
33+ * Big-O Analysis
34+ * Time Complexity
35+ - O(N^2) on average and worst case scenario
36+ - O(N) on best case scenario (when input array is already almost sorted)
37+ * Space Complexity
38+ - O(1)
39+ */
40+
41+ export function insertionSortAlternativeImplementation (array) {
42+ const length = array.length
43+ if (length < 2) return array
44+
45+ for (let i = 1; i < length; i++) {
46+ // Take current element in array
47+ const currentItem = array[i]
48+ // Take index of previous element in array
49+ let j = i - 1
50+
51+ // While j >= 0 and previous element is greater than current element
52+ while (j >= 0 && array[j] > currentItem) {
53+ // Move previous, greater element towards the unsorted part
54+ array[j + 1] = array[j]
55+ j--
56+ }
57+ // Insert currentItem number at the correct position in sorted part.
58+ array[j + 1] = currentItem
59+ }
60+ // Return array sorted in ascending order
61+ return array
62+ }
0 commit comments