Quicksort
Quicksort in C++
cpp
#include <stdio.h>
void println(int* p, int size) {
printf("{");
for (int i = 0; i < size; i++) {
printf("%d", p[i]);
if (i != size - 1) {
printf(",");
}
}
printf("}\n");
}
void exchange(int* A, int a, int b) {
int temp = A[a];
A[a] = A[b];
A[b] = temp;
}
int partition_sort(int* A, int p, int r) {
int X = A[r];
int i = p - 1;
for (int j = p; j <= r - 1; j++) {
if (A[j] <= X) {
i += 1;
exchange(A, i, j);
}
}
exchange(A, i+1, r);
return i + 1;
}
void _quicksort(int* A, int p, int r) {
if (p < r) {
int q = partition_sort(A, p, r);
_quicksort(A, p, q - 1);
_quicksort(A, q + 1, r);
}
}
void quicksort(int* arr, int size) {
_quicksort(arr, 0, size-1);
}
int main()
{
int arr[10] = { 0, 11, 2, 333, 4, 55, 6, 777 ,8, 99 };
int size = sizeof(arr) / sizeof(int);
println(arr, size);
quicksort(arr, size);
println(arr, size);
}
Quicksort in Rust
cpp
fn quicksort(arr: &mut [i32]) {
let end = arr.len() - 1;
_quicksort(arr, 0, end as isize);
}
fn _quicksort(arr: &mut [i32], start: isize, end: isize) {
if start < end {
let pi = partition_sort(arr, start, end);
_quicksort(arr, start, pi - 1);
_quicksort(arr, pi + 1, end);
}
}
fn partition_sort(arr: &mut [i32], start: isize, end: isize) -> isize {
println!("sorting: {:?}", arr);
let pi = start;
let mut i = pi + 1;
let mut j = i;
while j <= end {
if arr[j as usize] < arr[pi as usize] {
arr.swap(j as usize, i as usize);
i += 1;
}
j += 1;
}
arr.swap((i - 1) as usize, pi as usize);
i - 1
}
fn main() {
let mut arr = [3, 5, 8, 2, 1, 8, 21, 13, 1, 2];
println!("Before sorting: {:?}", arr);
quicksort(&mut arr);
println!("After sorted: {:?}", arr);
}