Skip to content

Commit fa1adfe

Browse files
committed
Insertion sort code added
1 parent 394154b commit fa1adfe

File tree

3 files changed

+63
-0
lines changed

3 files changed

+63
-0
lines changed

Sorting/Insertion Sort/README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
# Insertion Sort
2+
3+
**Insertion sort** does exactly what you would expect: it inserts each element of the array into its proper position, leaving progressively larger stretches of the array sorted. What this means in practice is that the sort iterates down an array, and the part of the array already covered is in order; then, the current element of the array is inserted into the proper position at the head of the array, and the rest of the elements are moved down, using the space just vacated by the element inserted as the final space.
4+
5+
![Insertion Sort](insertion_sort.jpg)
6+
7+
8+
#####A visualization on Insertion Sort
9+
![Insertion sort demonstration](https://upload.wikimedia.org/wikipedia/commons/0/0f/Insertion-sort-example-300px.gif)
10+
11+
12+
####Complexity Analysis
13+
- Worst Case - О(n<sup>2</sup>) comparisons, swaps
14+
- Average Case - О(n<sup>2</sup>) comparisons, swaps
15+
- Best Case - O(n) comparisons, O(1) swaps
16+
### More on this topic
17+
- https://en.wikipedia.org/wiki/Insertion_sort
18+
- http://quiz.geeksforgeeks.org/insertion-sort/
19+
- https://www.topcoder.com/community/data-science/data-science-tutorials/sorting/
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
//Insertion sort implementation
2+
function insertionSort(arr){
3+
var len = arr.length;
4+
5+
for(var i=1; i<len; i++){
6+
currentValue = arr[i];
7+
j = i-1;
8+
9+
/* Move elements of arr[0..i-1], that are
10+
greater than current_value, to one position ahead
11+
of their current position */
12+
while (j >= 0 && arr[j] > currentValue)
13+
{
14+
arr[j+1] = arr[j];
15+
j--;
16+
}
17+
arr[j+1] = currentValue;
18+
}
19+
20+
return arr;
21+
}
22+
23+
/******************* Testing Selection sort algorithm *********************/
24+
25+
/**
26+
* Returns a random integer between min (inclusive) and max (inclusive)
27+
* Using Math.round() will give you a non-uniform distribution!
28+
*/
29+
function getRandomInt(min, max) {
30+
return Math.floor(Math.random() * (max - min + 1)) + min;
31+
}
32+
33+
var arr = [];
34+
35+
for(var i=0;i<10;i++){ //initialize a random integer unsorted array
36+
arr.push(getRandomInt(1, 100));
37+
}
38+
39+
console.log("Unsorted array: ");
40+
console.log(arr); //printing unsorted array
41+
42+
arr = insertionSort(arr);
43+
console.log("Sorted array: ");
44+
console.log(arr); //printing sorted array
48.5 KB
Loading

0 commit comments

Comments
 (0)