Skip to content

Commit 636fc7f

Browse files
committed
add quick sort
1 parent e03b8a7 commit 636fc7f

File tree

3 files changed

+58
-10
lines changed

3 files changed

+58
-10
lines changed

src/main/kotlin/sort/QuickSort.kt

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package sort
2+
3+
import org.junit.Test
4+
import util.swap
5+
6+
// 随机数下,数学期望 NLogN
7+
// 无随机数情况,最差情况,单调序列 O(n*n) -> 由于划分值打得很偏
8+
object QuickSort {
9+
fun sort(array: IntArray) {
10+
rec(0, array.lastIndex, array)
11+
}
12+
13+
fun rec(l: Int, r: Int, array: IntArray) {
14+
if (!(l in array.indices && r in array.indices && l < r)) return
15+
16+
val arr = partition(l, r, array)
17+
rec(l, arr[0], array)
18+
rec(arr[1], r, array)
19+
}
20+
21+
fun partition(l: Int, r: Int, array: IntArray): IntArray {
22+
val k = array[r]
23+
var p1 = l - 1
24+
var p2 = l
25+
var p3 = r
26+
while (p2 < p3) {
27+
if (array[p2] < k) {
28+
array.swap(p2, ++p1)
29+
p2++
30+
} else if (array[p2] > k) {
31+
array.swap(p2, --p3)
32+
} else {
33+
p2++
34+
}
35+
}
36+
array.swap(r, p2)
37+
println(array.joinToString(","))
38+
return intArrayOf(p1, p2)
39+
}
40+
}

src/main/kotlin/sort/TestSort.kt

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ import org.junit.Test
55
import util.sameAs
66

77
class TestSort {
8-
private val arr = intArrayOf(2, 45, 3462, 34, 6, 34, 754, 45, 6, 2)
9-
108
@Test
119
fun testSelection() {
1210
repeat(5) {
@@ -41,13 +39,23 @@ class TestSort {
4139
}
4240

4341
@Test
44-
fun testMerge(){
42+
fun testMerge() {
4543
repeat(5) {
4644
var array1 = Logarithm.generateRandomArray(50, 50)
4745
var array2 = array1.clone()
4846
array1 = MergeSort.sort(array1)
4947
array2.sort()
50-
println("Merge sort:${array1.joinToString(",")}")
48+
Assert.assertTrue(array2.sameAs(array1))
49+
}
50+
}
51+
52+
@Test
53+
fun testQuick() {
54+
repeat(5) {
55+
val array1 = Logarithm.generateRandomArray(50, 50)
56+
val array2 = array1.clone()
57+
array2.sort()
58+
QuickSort.sort(array1)
5159
Assert.assertTrue(array2.sameAs(array1))
5260
}
5361
}

src/main/kotlin/util/Array.kt

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
package util
22

33
fun IntArray.swap(i: Int, j: Int) {
4-
this[i] = this[i] xor this[j]
5-
this[j] = this[i] xor this[j]
6-
this[i] = this[i] xor this[j]
7-
// val temp = this[i]
8-
// this[i] = this[j]
9-
// this[j] = temp
4+
// this[i] = this[i] xor this[j]
5+
// this[j] = this[i] xor this[j]
6+
// this[i] = this[i] xor this[j]
7+
val temp = this[i]
8+
this[i] = this[j]
9+
this[j] = temp
1010
}
1111

1212
fun IntArray.sameAs(intArray: IntArray): Boolean {

0 commit comments

Comments
 (0)