算法设计与分析实验指导(完整版)

本文介绍了算法设计与分析实验,重点探讨了快速排序及其优化,包括降低空间复杂度的尾递归和避免最坏情况的随机基准数。此外,还讲解了基于快排和堆排序的第k小数查找方法,以及棋盘覆盖、背包问题、照亮山景、汽车加油问题和最长公共子序列等经典算法问题,涉及动态规划和贪心策略的应用。

算法设计与分析实验指导

1. 快速排序及第k小数

1.1 快速排序

1.1.1 Implementation 1

核心代码如下:

int partition(vector<int> &nums, int l, int r) {
   
   
    int i = l;
    int j = r;
    while (i < j) {
   
   
        while (i < j && nums[j] >= nums[l]) j--;
        while (i < j && nums[i] <= nums[l]) i++;
        swap(nums[i], nums[j]);
    }
    swap(nums[i], nums[l]);
    return i;
}

void quickSort(vector<int> &nums, int l, int r) {
   
   
    if (l >= r) return;
    int i = partition(nums, l, r);
    quickSort(nums, l, i - 1);
    quickSort(nums, i + 1, r);
}

1.1.2 算法特性分析

时间复杂度:

最佳Ω(NlogN) : 最佳情况下, 每轮哨兵划分操作将数组划分为等长度的两个子数组;哨兵划分操作为线性时间复杂度 O(N);递归轮数共 O(logN) 。

平均Θ(NlogN) : 在随机输入数组下,哨兵划分操作的递归轮数也为O(logN) 。

最差 O(N^2): 在某些特殊输入数组下,每轮哨兵划分操作都将长度为 N 的数组划分为长度为1和N−1的两个子数组,此时递归轮数达到N 。

虽然平均时间复杂度与「归并排序」和「堆排序」一致,但在实际使用中快速排序 效率更高 ,这是因为:

最差情况稀疏性: 虽然快速排序的最差时间复杂度为 O(N^2),差于归并排序和堆排序,但统计意义上看,这种情况出现的机率很低。大部分情况下,快速排序以 O(NlogN) 复杂度运行。

缓存使用效率高: 哨兵划分操作时,将整个子数组加载入缓存中,访问元素效率很高;堆排序需要跳跃式访问元素,因此不具有此特性。

常数系数低: 在提及的三种算法中,快速排序的 比较、赋值、交换 三种操作的综合耗时最低(类似于插入排序快于冒泡排序的原理)。

原地: 不用借助辅助数组的额外空间,递归仅使用O(logN) 大小的栈帧空间。

非稳定: 哨兵划分操作可能改变相等元素的相对顺序。

自适应: 若每轮哨兵划分操作都将长度为 NN 的数组划分为长度1和N−1两个子数组,则时间复杂度劣化至O(N^2)。

1.1.3 Improvement 1: 降低空间复杂度——Tail Call

最坏情况进行N次递归,那么最差时间复杂度会达到O(N)。

每轮递归时,仅对 较短的子数组 执行哨兵划分 partition() ,就可将最差的递归深度控制在O(logN) (每轮递归的子数组长度都≤ 当前数组长度),即实现最差空间复杂度 O(logN) 。

代码只需修改quick_sort():

void quickSort(vector<int> &nums, int l, int r) {
   
   
	while (l < r) {
   
   
        int i = partition(nums, l, r);
        if (i - l < r - i) {
   
   
            quickSort(nums, l, i - 1);
            l = i + 1;
        }
        else {
   
   
            quickSort(nums, i + 1, r);
            r = i - 1;
        }
    }
}

1.1.3 Improvement 2:避免最坏情况——随机基准数

通过随机函数,随机选取哨兵值,极大程度避免完全有序或者完全倒序的情况下时间复杂度为O(n2)的情况。

partition()代码修改如下:

int partition(vector<int>& nums, int l, int r) {
   
   
    // 在闭区间 [l, r] 随机选取任意索引,并与 nums[l] 交换
    int ra = l + rand() % (r - l + 1);
    swap(nums[l], nums[ra]);
    // 以 nums[l] 作为基准数
    int i = l, j = r;
    while (i < j) {
   
   
        while (i < j && nums[j] >= nums[l]) j--;
        while (i < j && nums[i] <= nums[l]) i++;
        swap(nums[i], nums[j]);
    }
    swap(nums[i], nums[l]);
    return i;
}

1.2 第k小数

1.2.1 Implementation 1: 基于快排

继承快排的思想,当哨兵位置为k时返回对应值。

partition部分可以继续沿用1.1.3的改进,将quickSort段代码改成如下:

int kMin(vector<int>& nums, int l, int r, int k) {
   
   
    int i = partition(nums, l, r);
    if (i == k) {
   
   
        return nums[k];
    }
    if (i < k) {
   
   
        return kMin(nums, i + 1, r, k);
    }
    else return kMin(nums, l, i - 1, k);
}

该方法的时间复杂度为θ(n),但是最坏情况达到了O(n2)。

空间复杂度为O(logn),即递归调用栈空间的空间代价。

1.2.2 Implementation 2: 基于堆排序

堆的性质是每次弹出最小的一个值,那么找第k小的数,也就是调用k次堆的弹出函数。

堆的API如下:

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;


template<class T> class myHeap {
   
   
private:
    T* heap;
    int capacity;
    const int REFACTOR = 2;
    void heapSort(int n);
    void switchSons(int i, int size);
    void topDownHeapify(int maxPos);
public:
    myHeap();
    myHeap(T* array, int size);
    void insert(T item);
    void pop();
    void print();
    T peek();
};

template<class T> myHeap<T>::myHeap() {
   
   
    heap = new T[11];
    capacity = 10;
    heap[0] = 0;
}

template<class T> myHeap<T>::myHeap(T* array, int size) {
   
   
    heap = new T[size + 1];
    heap[0] = size;
    capacity = size;
    for (int i = 1; i <= size; i++) {
   
   
        heap[i] = array[i - 1];
    }
    heapSort(heap[0]);
}

template<class T> void myHeap<T>::heapSort(int size) {
   
   
    if (size == 1) return;
    int n = size / 2;
    for (int i = n; i >= 1; i--) {
   
   
        switchSons(i, size);
    }
    swap(heap[1], heap[size]);
    heapSort(size - 1);
}

template<class T> void myHeap<T>::switchSons(int i, int size) {
   
   
    if (2 * i + 1 > size) {
   
   
        if (heap[i] < heap[2 * i]) {
   
   
            swap(heap[i], heap[2 * i]);
        }
        return;
    }

    T left = heap[2 * i];
    T right = heap[2 * i + 1];

    if (right > left && right > heap[i]) {
   
   
        swap(heap[i], heap[2 * i + 1]);
    }
    else if (left > heap[i]) {
   
   
        swap(heap[i], heap[2 * i]);
    }
}

template<class T> void myHeap<T>::print() {
   
   
    for (int i = 1; i <= heap[0]; i++) {
   
   
        cout << heap[i] << " ";
    }
    cout << endl;
}

template<class T> void myHeap<T>::insert(T item) {
   
   
    if (heap[0] == capacity) {
   
   
        capacity *= REFACTOR;
        T* tmp = new T[capacity];
        for (int i = 0; i <= heap[0]; i++) {
   
   
            tmp[i] = heap[i];
        }
        heap = tmp;
    }
    heap[heap[0] + 1] = item;
    int i = heap[0]++ + 1;
    int j = heap[0] / 2;
    while (j >= 0 && i != 1) {
   
   
        if (heap[j] <= item) break;
        heap[i] = heap[j];
        i = j;
        j = i / 2;
    }
    heap[i] = item;
}

template<class T> void myHeap<T>::pop() {
   
   
    if (heap[0] == 0) return;
    // print();
    cout << heap[1] << endl;
    swap(heap[1], heap[heap[0]--]);
    // print();

    topDownHeapify
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值