Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit2c9c5a5

Browse files
authored
Update 0912-sort-an-array.kt
1 parent535ade4 commit2c9c5a5

File tree

1 file changed

+4
-5
lines changed

1 file changed

+4
-5
lines changed

‎kotlin/0912-sort-an-array.kt

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,9 +52,6 @@ class Solution {
5252

5353
/*
5454
* 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)
5855
*/
5956
classSolution {
6057
funsortArray(nums:IntArray):IntArray {
@@ -72,10 +69,12 @@ class Solution {
7269
}
7370

7471
privatefunpartition(nums:IntArray,low:Int,high:Int):Int {
72+
val r= (low..high).random()
73+
nums.swap(r, high)
7574
val pivot= nums[high]
7675
var i= low
7776

78-
for(jin low until high) {
77+
for(jin low until high) {
7978
if (nums[j]<= pivot) {
8079
nums.swap(i, j)
8180
i++
@@ -87,7 +86,7 @@ class Solution {
8786
}
8887

8988
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] }
9190
}
9291
}
9392

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp