@@ -52,9 +52,6 @@ class Solution {
52
52
53
53
/*
54
54
* Quick sort
55
- * This will fail testcase 17/19 (used to pass earlier, before adding new testcases), I still added it here for interest.
56
- * It fails on test case where we have an array with many elements of which all are 2's. This will have quicksort to run as
57
- * its worst case, which is O(n^2). But on average this will run O(nlogn)
58
55
*/
59
56
class Solution {
60
57
fun sortArray (nums : IntArray ):IntArray {
@@ -72,10 +69,12 @@ class Solution {
72
69
}
73
70
74
71
private fun partition (nums : IntArray ,low : Int ,high : Int ):Int {
72
+ val r= (low.. high).random()
73
+ nums.swap(r, high)
75
74
val pivot= nums[high]
76
75
var i= low
77
76
78
- for (jin low until high) {
77
+ for (jin low until high) {
79
78
if (nums[j]<= pivot) {
80
79
nums.swap(i, j)
81
80
i++
@@ -87,7 +86,7 @@ class Solution {
87
86
}
88
87
89
88
fun IntArray.swap (i : Int ,j : Int ) {
90
- this [i]= this [j].also {this [j]= this [i] }
89
+ this [i]= this [j].also {this [j]= this [i] }
91
90
}
92
91
}
93
92