Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2b74c16

Browse files
Merge pull request #7 from ms10398/master
Added Implementation of Insertion Sort
2 parents aa5f07c + 3bbcc84 commit 2b74c16

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

‎Sorts/insertionSort.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
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.
6+
*/
7+
function insertionSort(unsortedList) {
8+
var len = unsortedList.length;
9+
for (var i = 1; i < len; i++) {
10+
var tmp = unsortedList[i]; //Copy of the current element.
11+
/*Check through the sorted part and compare with the number in tmp. If large, shift the number*/
12+
for (var j = i - 1; j >= 0 && (unsortedList[j] > tmp); j--) {
13+
//Shift the number
14+
unsortedList[j + 1] = unsortedList[j];
15+
}
16+
//Insert the copied number at the correct position
17+
//in sorted part.
18+
unsortedList[j + 1] = tmp;
19+
}
20+
}
21+
22+
var arr = [5, 3, 1, 2, 4, 8, 3, 8];
23+
insertionSort(arr);
24+
console.log(arr);

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /