Skip to content

Commit 226a6a3

Browse files
authored
Add Exchange Sort (TheAlgorithms#318)
1 parent a5cf37c commit 226a6a3

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ These are for demonstration purposes only.
1313
- [x] [Cocktail-Shaker](./src/sorting/cocktail_shaker_sort.rs)
1414
- [x] [Counting](./src/sorting/counting_sort.rs)
1515
- [x] [Cycle](./src/sorting/cycle_sort.rs)
16+
- [x] [Exchange](./src/sorting/exchange_sort.rs)
1617
- [x] [Heap](./src/sorting/heap_sort.rs)
1718
- [x] [Insertion](./src/sorting/insertion_sort.rs)
1819
- [x] [Gnome](./src/sorting/gnome_sort.rs)

src/sorting/exchange_sort.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// sorts through swapping the first value until it is at the right position, and repeating for all the following.
2+
3+
pub fn exchange_sort(arr: &mut [i32]) {
4+
let length = arr.len();
5+
for number1 in 0..length {
6+
for number2 in (number1 + 1)..length {
7+
if arr[number2] < arr[number1] {
8+
arr.swap(number1, number2)
9+
}
10+
}
11+
}
12+
}
13+
14+
#[cfg(test)]
15+
mod tests {
16+
use super::super::is_sorted;
17+
use super::*;
18+
#[test]
19+
fn it_works() {
20+
let mut arr1 = [6, 5, 4, 3, 2, 1];
21+
exchange_sort(&mut arr1);
22+
assert!(is_sorted(&arr1));
23+
arr1 = [12, 343, 21, 90, 3, 21];
24+
exchange_sort(&mut arr1);
25+
assert!(is_sorted(&arr1));
26+
let mut arr2 = [1];
27+
exchange_sort(&mut arr2);
28+
assert!(is_sorted(&arr2));
29+
let mut arr3 = [213, 542, 90, -23412, -32, 324, -34, 3324, 54];
30+
exchange_sort(&mut arr3);
31+
assert!(is_sorted(&arr3));
32+
}
33+
}

src/sorting/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ mod cocktail_shaker_sort;
44
mod comb_sort;
55
mod counting_sort;
66
mod cycle_sort;
7+
mod exchange_sort;
78
mod gnome_sort;
89
mod heap_sort;
910
mod insertion_sort;
@@ -24,6 +25,7 @@ pub use self::comb_sort::comb_sort;
2425
pub use self::counting_sort::counting_sort;
2526
pub use self::counting_sort::generic_counting_sort;
2627
pub use self::cycle_sort::cycle_sort;
28+
pub use self::exchange_sort::exchange_sort;
2729
pub use self::gnome_sort::gnome_sort;
2830
pub use self::heap_sort::heap_sort;
2931
pub use self::insertion_sort::insertion_sort;

0 commit comments

Comments
 (0)