| ... | ... | @@ -0,0 +1,65 @@ |
| 1 | const assert = @import("debug.zig").assert; |
| 2 | const str = @import("str.zig"); |
| 3 | |
| 4 | pub fn sort(inline T: type, array: []T) { |
| 5 | if (array.len > 0) { |
| 6 | quicksort(T, array, 0, array.len - 1); |
| 7 | } |
| 8 | } |
| 9 | |
| 10 | fn quicksort(inline T: type, array: []T, left: usize, right: usize) { |
| 11 | var i = left; |
| 12 | var j = right; |
| 13 | var p = (i + j) / 2; |
| 14 | |
| 15 | while (i <= j) { |
| 16 | while (array[i] < array[p]) { |
| 17 | i += 1; |
| 18 | } |
| 19 | while (array[j] > array[p]) { |
| 20 | j -= 1; |
| 21 | } |
| 22 | if (i <= j) { |
| 23 | const tmp = array[i]; |
| 24 | array[i] = array[j]; |
| 25 | array[j] = tmp; |
| 26 | i += 1; |
| 27 | if (j > 0) j -= 1; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | if (left < j) quicksort(T, array, left, j); |
| 32 | if (i < right) quicksort(T, array, i, right); |
| 33 | } |
| 34 | |
| 35 | fn testSort() { |
| 36 | @setFnTest(this, true); |
| 37 | |
| 38 | const u8cases = [][][]u8 { |
| 39 | [][]u8{"", ""}, |
| 40 | [][]u8{"a", "a"}, |
| 41 | [][]u8{"az", "az"}, |
| 42 | [][]u8{"za", "az"}, |
| 43 | [][]u8{"asdf", "adfs"}, |
| 44 | [][]u8{"one", "eno"}, |
| 45 | }; |
| 46 | |
| 47 | for (u8cases) |case| { |
| 48 | sort(u8, case[0]); |
| 49 | assert(str.eql(case[0], case[1])); |
| 50 | } |
| 51 | |
| 52 | const i32cases = [][][]i32 { |
| 53 | [][]i32{[]i32{}, []i32{}}, |
| 54 | [][]i32{[]i32{1}, []i32{1}}, |
| 55 | [][]i32{[]i32{0, 1}, []i32{0, 1}}, |
| 56 | [][]i32{[]i32{1, 0}, []i32{0, 1}}, |
| 57 | [][]i32{[]i32{1, -1, 0}, []i32{-1, 0, 1}}, |
| 58 | [][]i32{[]i32{2, 1, 3}, []i32{1, 2, 3}}, |
| 59 | }; |
| 60 | |
| 61 | for (i32cases) |case| { |
| 62 | sort(i32, case[0]); |
| 63 | assert(str.sliceEql(i32, case[0], case[1])); |
| 64 | } |
| 65 | } |