initial zad4 work

This commit is contained in:
jacekpoz 2024-04-09 23:24:04 +02:00
parent b59437d3c7
commit a5198e7c49
Signed by: poz
SSH key fingerprint: SHA256:JyLeVWE4bF3tDnFeUpUaJsPsNlJyBldDGV/dIKSLyN8
4 changed files with 106 additions and 0 deletions

1
lab2/zad4/.gitignore vendored Normal file
View file

@ -0,0 +1 @@
target/

14
lab2/zad4/Cargo.lock generated Normal file
View file

@ -0,0 +1,14 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "libsort"
version = "0.1.0"
[[package]]
name = "zad4"
version = "0.1.0"
dependencies = [
"libsort",
]

7
lab2/zad4/Cargo.toml Normal file
View file

@ -0,0 +1,7 @@
[package]
name = "zad4"
version = "0.1.0"
edition = "2021"
[dependencies]
libsort = { path = "../zad1/libsort" }

84
lab2/zad4/src/main.rs Normal file
View file

@ -0,0 +1,84 @@
use libsort::{quick_sort, SortResult};
#[derive(PartialEq)]
enum CompareResult {
LESS, EQUAL, GREATER
}
fn compare(a: u64, b: u64, comparisons: &mut u64) -> CompareResult {
*comparisons += 1;
if a < b {
CompareResult::LESS
} else if a > b {
CompareResult::GREATER
} else {
CompareResult::EQUAL
}
}
fn swap(list: &mut [u64], i: usize, j: usize, swaps: &mut u64) {
*swaps += 1;
list.swap(i, j);
}
use CompareResult::*;
fn dual_pivot_partition(list: &mut [u64], res: &mut SortResult) -> (usize, usize) {
let mut comps = 0;
let mut swaps = 0;
if compare(list[0], list[list.len() - 1], &mut comps) == GREATER {
swap(list, 0, list.len() - 1, &mut swaps);
}
let mut l = 1;
let mut g = list.len() - 2;
let mut k = l;
let p = list[0];
let q = list[list.len()];
while k <= g {
if compare(list[k], p, &mut comps) == LESS {
swap(list, k, l, &mut swaps);
l += 1;
} else if compare(list[k], q, &mut comps) != LESS {
while compare(list[g], q, &mut comps) == GREATER && k < g {
g -= 1;
}
swap(list, k, g, &mut swaps);
g -= 1;
if compare(list[k], p, &mut comps) == LESS {
swap(list, k, l, &mut swaps);
l += 1;
}
}
k += 1;
}
l -= 1;
g += 1;
swap(list, 0, l, &mut swaps);
swap(list, list.len() - 1, g, &mut swaps);
res.comparisons += comps;
res.swaps += swaps;
(l, g)
}
fn dual_pivot_quick_sort(list: &mut [u64]) -> SortResult {
let mut res = SortResult::default();
let (lp, rp) = dual_pivot_partition(list, &mut res);
let res1 = dual_pivot_quick_sort(&mut list[..(lp - 1)]);
let res2 = dual_pivot_quick_sort(&mut list[(lp + 1)..=(rp - 1)]);
let res3 = dual_pivot_quick_sort(&mut list[(rp + 1)..]);
res.comparisons += res1.comparisons + res2.comparisons + res3.comparisons;
res.swaps += res1.swaps + res2.swaps + res3.swaps;
res
}
fn main() {
}