Created
March 26, 2017 14:39
-
-
Save zeraf29/240abd4c4f3602be9d1df6cd765fa806 to your computer and use it in GitHub Desktop.
[칸 아카데미] 알고리즘-삽입정렬 : 삽입구현 소스
This file contains hidden or 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
var insert = function(array, rightIndex, value) { | |
//Compare values between array[rightIndex] and value. | |
//if value is smaller than array[rightIndex], that array's value will be copied to array[rightIndex+1]. | |
//This work keep going until finding value is bigger than array[i]("for" loop) | |
//if find smaller array value or i reach 0, loop will be end and value will be copied to array[i+1] | |
var i; | |
for(i=rightIndex;i>=0&&array[i]>value;i--){ | |
array[i+1]=array[i]; | |
} | |
array[i+1]=value; | |
}; | |
var array = [3, 5, 7, 11, 13, 2, 9, 6]; | |
insert(array, 4, 2); | |
println("Array after inserting 2: " + array); | |
Program.assertEqual(array, [2, 3, 5, 7, 11, 13, 9, 6]); | |
insert(array, 5, 9); | |
println("Array after inserting 9: " + array); | |
Program.assertEqual(array, [2, 3, 5, 7, 9, 11, 13, 6]); | |
insert(array, 6, 6); | |
println("Array after inserting 6: " + array); | |
Program.assertEqual(array, [2, 3, 5, 6, 7, 9, 11, 13]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment