forked from jainaman224/Algo_Ds_Notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertion_Sort.kt
More file actions
27 lines (25 loc) · 806 Bytes
/
Insertion_Sort.kt
File metadata and controls
27 lines (25 loc) · 806 Bytes
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
//Function for sorting an list using Insertion Sort
fun Insertion_sort(list: MutableList<Int>): List<Int> {
for(i in 0 until list.size) {
var key = list[i]
var j = i - 1
/*Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position*/
while(j > 0 && list[j] > key) {
list[j+1] = list[j]
j = j - 1
}
list[j+1] = key
}
return list
}
//Driver function for Insertion sort
fun main(args: Array<String>) {
val list = mutableListOf(4, 67, 89, 2, 45, 102)
println("Unsorted List: $list")
val sortedlist = Insertion_sort(list)
println("Sorted List: $sortedlist")
}
//Input: Unsorted: [4, 67, 89, 2, 45, 102]
//Output: Sorted: [2, 4, 25, 67, 89, 102]