从0开始学习C++ 第三十课 插入排序和快速排序

本文介绍了插入排序和快速排序这两种常见的排序算法,包括它们的工作原理、C++代码示例以及时间复杂度、空间复杂度和稳定性分析。快速排序虽然效率高但不稳定,可通过优化基准元素选择提高性能。
摘要由CSDN通过智能技术生成

插入排序 (Insertion Sort)

概念:
插入排序是一种简单直观的排序算法,它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。

逐步分析:

  1. 从数组第二个元素开始遍历,因为单个元素默认是已排序的。
  2. 取出当前元素,与其之前的元素比较,如果之前的元素更大,则将之前的元素后移。
  3. 重复步骤2,直到找到一个元素小于或等于当前元素。
  4. 将当前元素插入到该位置。
  5. 重复步骤2-4,直到数组结束。

C++ 代码示例:

#include <iostream>
#include <vector>

void insertionSort(std::vector<int>& arr) {
    int n = arr.size();
    for (int i = 1; i < n; i++) {
        int key = arr[i];
        int j = i - 1;

        // Move elements of arr[0..i-1], that are greater than key,
        // to one position ahead of their current position
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

int main() {
    std::vector<int> arr = {12, 11, 13, 5, 6};
    insertionSort(arr);
    for (int num : arr) {
        std::cout << num << " ";
    }
    return 0;
}

时间复杂度: 最好情况 O(n)(数组已经是有序的),平均和最坏情况 O(n^2)
空间复杂度: O(1)
是否稳定: 是,因为它不会改变相同元素的初始相对顺序。

快速排序 (Quick Sort)

概念:
快速排序是一种高效的排序算法,利用分治法对数组进行快速排序。选定一个元素作为"基准"(pivot),元素比基准小的放在基准前面,比基准大的放在基准后面,相同则任一边均可。

逐步分析:

  1. 选择数组中的一个元素作为基准(pivot)。
  2. 重新排列数组元素,所有比基准小的放前面,所有比基准大的放后面,相同的任一边。
  3. 分别对前后两部分递归执行以上步骤。
  4. 递归终止条件是子数组长度为1或0。

C++ 代码示例:

#include <iostream>
#include <vector>

void quickSortRecursive(std::vector<int>& arr, int start, int end) {
    if (start >= end) return;

    int pivot = arr[end]; // Choosing the last element as the pivot
    int left = start;
    int right = end - 1;

    while (left < right) {
        // Find the first element greater than the pivot
        while (arr[left] < pivot && left < right) left++;
        // Find the first element less than the pivot
        while (arr[right] >= pivot && left < right) right--;

        std::swap(arr[left], arr[right]);
    }

    if (arr[left] >= pivot)
        std::swap(arr[left], arr[end]);
    else
        left++;

    // Recursively sort the elements before partition and after partition
    quickSortRecursive(arr, start, left - 1);
    quickSortRecursive(arr, left + 1, end);
}

void quickSort(std::vector<int>& arr) {
    quickSortRecursive(arr, 0, arr.size() - 1);
}

int main() {
    std::vector<int> arr = {10, 7, 8, 9, 1, 5};
    quickSort(arr);
    for (int num : arr) {
        std::cout << num << " ";
    }
    return 0;
}

时间复杂度: 平均情况 O(n log n),最坏情况 O(n^2)
空间复杂度: O(log n)(递归栈空间)
是否稳定: 否,因为相等的元素可能会因为分区而交换,导致相对顺序改变。

快速排序的最坏情况发生在每次分区操作都将数组分为两个部分,其中一个为空,这通常在数组已经是升序或降序时发生。 若要优化快速排序,可以采用“三数取中”或“随机化”来选择基准元素,减少算法陷入最坏情况的概率。

目录
第三十一课 归并排序和堆排序

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值