This repository has been archived by the owner on Oct 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 178
/
Copy pathShellSort.kt
63 lines (55 loc) · 1.87 KB
/
ShellSort.kt
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Java implementation of ShellSort
class ShellSort {
/* function to sort arr using shellSort */
fun sort(arr: IntArray): Int {
val n = arr.size
// Start with a big gap, then reduce the gap
var gap = n / 2
while (gap > 0) {
// Do a gapped insertion sort for this gap size.
// The first gap elements a[0..gap-1] are already
// in gapped order keep adding one more element
// until the entire array is gap sorted
var i = gap
while (i < n) {
// add a[i] to the elements that have been gap
// sorted save a[i] in temp and make a hole at
// position i
val temp = arr[i]
// shift earlier gap-sorted elements up until
// the correct location for a[i] is found
var j: Int
j = i
while (j >= gap && arr[j - gap] > temp) {
arr[j] = arr[j - gap]
j -= gap
}
// put temp (the original a[i]) in its correct
// location
arr[j] = temp
i += 1
}
gap /= 2
}
return 0
}
companion object {
/* An utility function to print array of size n*/
fun printArray(arr: IntArray) {
val n = arr.size
for (i in 0 until n)
System.out.print(arr[i].toString() + " ")
System.out.println()
}
// Driver method
fun main(args: Array<String>) {
val arr = intArrayOf(12, 34, 54, 2, 3)
System.out.println("Array before sorting")
printArray(arr)
val ob = ShellSort()
ob.sort(arr)
System.out.println("Array after sorting")
printArray(arr)
}
}
}