authorgravatar for steve@octopart.comSteve Perkins <steve@octopart.com> 2016-11-02 18:52:00-04:00
committergravatar for steve@octopart.comSteve Perkins <steve@octopart.com> 2016-11-02 18:52:00-04:00
loge761aa2d2f0034b1b6a071c4dae5262ef96997fb
treee18d4fb0fb5b38a0f1d7de76683bd80c69818b4e
parentc5b2bdae112d37a6ed7ca7010752f048f08b1e27

sortCmp allows for a custom cmp function


1 files changed, 81 insertions(+), 0 deletions(-)

std/sort.zig+81
......@@ -1,5 +1,8 @@
11const assert = @import("debug.zig").assert;
22const str = @import("str.zig");
3const math = @import("math.zig");
4
5pub const Cmp = math.Cmp;
36
47pub fn sort(inline T: type, array: []T) {
58 if (array.len > 0) {
......@@ -32,6 +35,43 @@ fn quicksort(inline T: type, array: []T, left: usize, right: usize) {
3235 if (i < right) quicksort(T, array, i, right);
3336}
3437
38// ---------------------------------------
39// sortCmp
40
41pub fn sortCmp(inline T: type, array: []T, inline cmp: fn(a: T, b: T)->Cmp) {
42 if (array.len > 0) {
43 quicksortCmp(T, array, 0, array.len - 1, cmp);
44 }
45}
46
47fn quicksortCmp(inline T: type, array: []T, left: usize, right: usize, inline cmp: fn(a: T, b: T)->Cmp) {
48 var i = left;
49 var j = right;
50 var p = (i + j) / 2;
51
52 while (i <= j) {
53 while (cmp(array[i], array[p]) == Cmp.Less) {
54 i += 1;
55 }
56 while (cmp(array[j], array[p]) == Cmp.Greater) {
57 j -= 1;
58 }
59 if (i <= j) {
60 const tmp = array[i];
61 array[i] = array[j];
62 array[j] = tmp;
63 i += 1;
64 if (j > 0) j -= 1;
65 }
66 }
67
68 if (left < j) quicksortCmp(T, array, left, j, cmp);
69 if (i < right) quicksortCmp(T, array, i, right, cmp);
70}
71
72// ---------------------------------------
73// tests
74
3575fn testSort() {
3676 @setFnTest(this, true);
3777
......@@ -63,3 +103,44 @@ fn testSort() {
63103 assert(str.sliceEql(i32, case[0], case[1]));
64104 }
65105}
106
107fn testSortCmp() {
108 @setFnTest(this, true);
109
110 const i32cases = [][][]i32 {
111 [][]i32{[]i32{}, []i32{}},
112 [][]i32{[]i32{1}, []i32{1}},
113 [][]i32{[]i32{0, 1}, []i32{0, 1}},
114 [][]i32{[]i32{1, 0}, []i32{0, 1}},
115 [][]i32{[]i32{1, -1, 0}, []i32{-1, 0, 1}},
116 [][]i32{[]i32{2, 1, 3}, []i32{1, 2, 3}},
117 };
118
119 for (i32cases) |case| {
120 sortCmp(i32, case[0], normalCmp);
121 assert(str.sliceEql(i32, case[0], case[1]));
122 }
123
124 const revCases = [][][]i32 {
125 [][]i32{[]i32{}, []i32{}},
126 [][]i32{[]i32{1}, []i32{1}},
127 [][]i32{[]i32{0, 1}, []i32{1, 0}},
128 [][]i32{[]i32{1, 0}, []i32{1, 0}},
129 [][]i32{[]i32{1, -1, 0}, []i32{1, 0, -1}},
130 [][]i32{[]i32{2, 1, 3}, []i32{3, 2, 1}},
131 };
132
133 for (revCases) |case| {
134 sortCmp(i32, case[0], revCmp);
135 assert(str.sliceEql(i32, case[0], case[1]));
136 }
137
138}
139
140fn normalCmp(a: i32, b: i32) -> Cmp {
141 return if (a > b) Cmp.Greater else if (a < b) Cmp.Less else Cmp.Equal;
142}
143
144fn revCmp(a: i32, b: i32) -> Cmp {
145 return if (a < b) Cmp.Greater else if (a > b) Cmp.Less else Cmp.Equal;
146}