Skip to content
 算法

排序:复杂度及其证明

Updated: at 00:00:00Suggest Changes

冒泡排序

时间复杂度

代码

pub fn bubble<T: Ord>(arr: &mut [T]) {
    for out in 1..arr.len() {
        let mut swapped = false;

        for i in 0..(arr.len() - out) {
            if arr[i] > arr[i + 1] {
                arr.swap(i, i + 1);

                swapped = true;
            }
        }

        if !swapped {
            break;
        }
    }
}

证明

选择排序

时间复杂度

代码:

pub fn selection<T: Ord>(arr: &mut [T]) {
    for left in 0..arr.len() {
        let min = (left..arr.len())
                  .min_by_key(|&i| arr.index(i))
                  .unwrap();
        arr.swap(left, min);
    }
}

论证

插入排序

时间复杂度

代码

pub fn insertion<T: Ord>(arr: &mut [T]) {
    for out in 1..arr.len() {
        let mut n = out;
        while out > 0 && arr[n] < arr[n - 1] {
            arr.swap(n, n - 1);

            n -= 1;
        }
    }
}

论证

归并排序

时间复杂度

空间复杂度

需要辅助数组,乃 O(n)O(n)

代码

use std::mem;

pub fn msort<T: Ord + Clone>(arr: &mut [T]) {
    let mut aux: Vec<T> = arr.into();

    merge(arr, &mut aux);
}

fn merge<T: Ord + Clone>(arr: &mut [T], aux: &mut [T]) {
    let len = arr.len();

    if len < 2 {
        return;
    }

    let mid = len / 2;

    let (arr_l, arr_r) = arr.split_at_mut(mid);
    let (aux_l, aux_r) = aux.split_at_mut(mid);

    merge(arr_l, aux_l);
    merge(arr_r, aux_r);

    let mut left = 0;
    let mut right = mid;

    for x in aux.iter_mut() {
        if left >= mid || (right < len && arr[left] > arr[right]) {
            mem::swap(x, &mut arr[right]);
            right += 1;
        } else {
            mem::swap(x, &mut arr[left]);
            left += 1;
        }
    }

    arr.clone_from_slice(aux);
}

论证

堆排序

时间复杂度

代码

fn sink<T: Ord>(arr: &mut [T], mut parent: usize) {
    let last = arr.len() - 1;

    loop {
        let left = 2 * parent + 1;

        if left > last {
            break;
        }

        let right = left + 1;

        let max = match left != last && arr[right] > arr[left] {
            true => right,
            false => left,
        };

        if arr[parent] < arr[max] {
            arr.swap(parent, max);
        }

        parent = max;
    }
}

pub fn heap<T: Ord>(arr: &mut [T]) {
    let len = arr.len();

    if len < 2 {
        return;
    }

    for parent in (0..=len / 2 - 1).rev() {
        sink(arr, parent);
    }

    for end in (1..len).rev() {
        arr.swap(0, end);

        sink(&mut arr[..end], 0);
    }
}

论证


Previous Post
M叉树之高
Next Post
线性筛