forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Added Insertion Sort [JavaScript] (iiitv#394)
* Added Insertion Sort [JavaScript] * bot fix v1.0
- Loading branch information
Showing
2 changed files
with
31 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
/* Following algorithm sorts the input array in ascending order | ||
* Time Complexity : O(n^2) | ||
* Auxiliary Space: O(1) | ||
* n is the number of elements in the array to be sorted | ||
*/ | ||
|
||
function insertionSort (arr) { | ||
/* | ||
: param arr : Array to be sorted | ||
: return : Sorted Array | ||
*/ | ||
for (let i = 1; i < arr.length; i++) { | ||
let j = i - 1; | ||
let temp = arr[i]; | ||
while (j >= 0 && arr[j] > temp) { | ||
arr[j + 1] = arr[j]; | ||
j--; | ||
} | ||
arr[j + 1] = temp; | ||
} | ||
return arr; | ||
} | ||
|
||
function main () { | ||
let arr = [5, 9, 3, 1, 99]; | ||
arr = insertionSort(arr); | ||
console.log(arr); | ||
} | ||
|
||
main(); |