Guest User

Untitled

a guest
Oct 18th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. package main.dataStructures.sorting
  2.  
  3. fun main(args: Array<String>) {
  4. val array = readLine()!!.split(" ").map { it.toInt() }.toIntArray() // 1) Read the input and split into array
  5. quickSort(array, 0, array.size-1)
  6. for(i in array) println(i)
  7. }
  8.  
  9. fun quickSort(array: IntArray, left: Int, right: Int) {
  10. val index = partition (array, left, right)
  11. if(left < index-1) { // 2) Sorting left half
  12. quickSort(array, left, index-1)
  13. }
  14. if(index < right) { // 3) Sorting right half
  15. quickSort(array,index, right)
  16. }
  17. }
  18.  
  19. fun partition(array: IntArray, l: Int, r: Int): Int {
  20. var left = l
  21. var right = r
  22. val pivot = array[(left + right)/2] // 4) Pivot Point
  23. while (left <= right) {
  24. while (array[left] < pivot) left++ // 5) Find the elements on left that should be on right
  25.  
  26. while (array[right] > pivot) right-- // 6) Find the elements on right that should be on left
  27.  
  28. // 7) Swap elements, and move left and right indices
  29. if (left <= right) {
  30. swapArray(array, left,right)
  31. left++
  32. right--
  33. }
  34. }
  35. return left
  36. }
  37.  
  38. fun swapArray(a: IntArray, b: Int, c: Int) {
  39. val temp = a[b]
  40. a[b] = a[c]
  41. a[c] = temp
  42. }
Add Comment
Please, Sign In to add comment