Skip to content

Commit

Permalink
added quick sort
Browse files Browse the repository at this point in the history
Signed-off-by: yourarj <[email protected]>

 Date:      Thu Jan 4 08:26:20 2024 +0530

 On branch main

 Changes to be committed:
	modified:   Cargo.lock
	modified:   sorting-algorithms/Cargo.toml
	modified:   sorting-algorithms/src/lib.rs
	new file:   sorting-algorithms/src/quick_sort.rs
  • Loading branch information
yourarj committed Jan 4, 2024
1 parent 5293182 commit 0d7a1f2
Show file tree
Hide file tree
Showing 4 changed files with 84 additions and 3 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion sorting-algorithms/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "merge-sort"
name = "sorting-algorithms"
version = "0.1.0"
edition = "2021"

Expand Down
1 change: 1 addition & 0 deletions sorting-algorithms/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
pub mod insertion_sort;
pub mod merge_sort;
pub mod quick_sort;
80 changes: 80 additions & 0 deletions sorting-algorithms/src/quick_sort.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
pub fn sort(arr: &mut [i32]) {
if arr.is_empty() {
return;
}
quick_sort(arr, 0, (arr.len() - 1) as isize);
}

fn quick_sort(arr: &mut [i32], start: isize, end: isize) {
if start > end {
return;
}

let pivot = arr[(start + (end - start) / 2) as usize];
let mut new_start = start;
let mut new_end = end;

while new_start <= new_end {
while arr[new_start as usize] < pivot {
new_start += 1;
}

while arr[new_end as usize] > pivot {
new_end -= 1;
}

if new_start <= new_end {
arr.swap(new_start as usize, new_end as usize);
new_start += 1;
new_end -= 1;
}
}

quick_sort(arr, start, new_end);
quick_sort(arr, new_start, end);
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn should_sort_reversed_array() {
let mut arr = [5, 4, 3, 2, 1, 0];
sort(&mut arr);

assert_eq!(arr[0], 0);
assert_eq!(arr[3], 3);
assert_eq!(arr[5], 5);
}

#[test]
fn should_sort_array_with_positive_negative_and_zero_numbers() {
let mut arr = [5, -4, 3, 2, -1, 0];
sort(&mut arr);

assert_eq!(arr[0], -4);
assert_eq!(arr[1], -1);
assert_eq!(arr[2], 0);
assert_eq!(arr[3], 2);
assert_eq!(arr[4], 3);
assert_eq!(arr[5], 5);
}

#[test]
fn should_not_touch_empty_array() {
let mut arr = [];
sort(&mut arr);
assert!(arr.is_empty());
}

#[test]
fn should_sort_array_with_multiple_duplicates_and_some_uniques() {
let mut arr = [5, 5, 5, 4, 4, 2, 2, 2, 2, 1, 0];
sort(&mut arr);

assert_eq!(arr[0], 0);
assert_eq!(arr[3], 2);
assert_eq!(arr[5], 2);
}
}

0 comments on commit 0d7a1f2

Please sign in to comment.