-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionSort.js
More file actions
66 lines (52 loc) · 1.93 KB
/
insertionSort.js
File metadata and controls
66 lines (52 loc) · 1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
function insertionSort(arr) {
const n = arr.length;
for (let i = 1; i < n; i++) {
let key = arr[i]; // Current element to be inserted
let j = i - 1; // Index of the last element in sorted portion
// Move elements of arr[0..i-1] that are greater than key
// one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
// Place key at its correct position
arr[j + 1] = key;
}
return arr;
}
// Alternative implementation with more explicit shifting
function insertionSortVerbose(arr) {
for (let i = 1; i < arr.length; i++) {
let current = arr[i];
let position = i;
// Shift elements to the right until we find the correct position
while (position > 0 && arr[position - 1] > current) {
arr[position] = arr[position - 1];
position--;
}
// Insert the current element at its correct position
arr[position] = current;
}
return arr;
}
// Version that doesn't modify the original array
function insertionSortCopy(arr) {
const copy = [...arr];
return insertionSort(copy);
}
// Example usage
const numbers = [64, 34, 25, 12, 22, 11, 90];
console.log("Original array:", numbers);
const sorted = insertionSortCopy(numbers);
console.log("Sorted array:", sorted);
// Test with different scenarios
const almostSorted = [1, 3, 2, 4, 6, 5, 7];
console.log("Almost sorted:", almostSorted);
console.log("After insertion sort:", insertionSortCopy(almostSorted));
const reversed = [9, 8, 7, 6, 5, 4, 3, 2, 1];
console.log("Reversed array:", reversed);
console.log("After insertion sort:", insertionSortCopy(reversed));
// Works with strings too
const words = ['zebra', 'apple', 'banana', 'cherry'];
console.log("Original words:", words);
console.log("Sorted words:", insertionSortCopy(words));