Skip to content

Commit d0f1555

Browse files
committed
Add quick sort.rs
1 parent 8444fda commit d0f1555

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

Diff for: labocédai/src/lib.rs

+15
Original file line numberDiff line numberDiff line change
@@ -208,5 +208,20 @@ mod tests {
208208
assert_eq!(merge_sort(&mut [1]), [1]);
209209
}
210210

211+
#[test]
212+
fn test_quick_sort() {
213+
assert_eq!(
214+
quick_sort(&mut [29, 10, 14, 30, 37, 14, 18]),
215+
[10, 14, 14, 18, 29, 30, 37]
216+
);
217+
assert_eq!(
218+
quick_sort(&mut [-1, -2, 1, 0]),
219+
[-2, -1, 0, 1]
220+
);
221+
assert_eq!(quick_sort(&mut []), []);
222+
assert_eq!(quick_sort(&mut [1, 1, 1, 2, 1]), [1, 1, 1, 1, 2]);
223+
assert_eq!(quick_sort(&mut [2, 1, 1, 1, 2]), [1, 1, 1, 2, 2]);
224+
assert_eq!(quick_sort(&mut [1]), [1]);
225+
}
211226
}
212227
}

Diff for: labocédai/src/sort.rs

+34
Original file line numberDiff line numberDiff line change
@@ -78,3 +78,37 @@ pub fn merge_sort(nums: &[isize]) -> Vec<isize> {
7878
let right = merge_sort(&nums[midpoint..]);
7979
merge(&left, &right)
8080
}
81+
82+
fn pivot_helper(nums: &mut [isize], start: usize, end: usize) -> usize {
83+
/* selects a pivot and arranges all nums less than it to the left of it,
84+
and greater than it to the right of it */
85+
let pivot_idx = start;
86+
let mut offset = start;
87+
for i in start+1..=end {
88+
if nums[i] < nums[pivot_idx] {
89+
offset += 1;
90+
nums.swap(i, offset);
91+
}
92+
}
93+
nums.swap(pivot_idx, offset);
94+
offset
95+
}
96+
97+
pub fn quick_sort(nums: &mut [isize]) -> &mut [isize] {
98+
fn sort(nums: &mut [isize], left: usize, right: usize) -> &mut [isize] {
99+
if left < right {
100+
let pivot_idx = pivot_helper(nums, left, right);
101+
// left
102+
if pivot_idx > 0 {
103+
sort(nums, left, pivot_idx - 1);
104+
}
105+
// right
106+
sort(nums, pivot_idx+1, right);
107+
}
108+
nums
109+
}
110+
if nums.len() > 0 {
111+
sort(nums, 0, nums.len() - 1);
112+
}
113+
nums
114+
}

0 commit comments

Comments
 (0)