Last active
October 17, 2018 11:33
-
-
Save vamsitallapudi/dfe55849ea78612100a6f058942bb50e 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
package main.dataStructures.sorting | |
fun main(args: Array<String>) { | |
var numSwaps = 0 | |
var isSorted = false | |
val str = readLine()!! | |
val intList: ArrayList<Int> = ArrayList(str.split(" ").map { it.toInt() }) //1) read values and convert them to arraylist | |
var lastUnsorted = intList.size - 1 // 2) to keep the track of unsorted array | |
while (!isSorted) { | |
isSorted = true | |
for (i in 0 until lastUnsorted) { | |
if (intList[i] > intList[i + 1]) { | |
swapValues(intList, i, i + 1) | |
numSwaps++ | |
isSorted = false // 3) making this as false whenever the swap needs to be performed. | |
} | |
} | |
lastUnsorted--// 4) decreasing the count since one more element from right side is placed in sorted position | |
} | |
for(i in intList) { | |
println(i) | |
} | |
} | |
fun swapValues(list: ArrayList<Int>, a: Int, b: Int) { | |
val temp = list[b] | |
list[b] = list[a] | |
list[a] = temp | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment