快速排序

本文介绍了一种插入排序算法的实现方法,并通过一个具体的例子展示了排序的过程。文章中使用了C++语言进行编码,详细解释了如何通过交换元素来完成数组的排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

快速排序类似于抓扑克,依次比较排序完成的数组,将当前数插在合适的位置
时间复杂度O(n*n)

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

void insert_sort(int *a, int left, int right);
void exch(int &e1, int &e2);

int main()
{
    int tmp, iCount = 0;
    int a[8] = {2,3,1,4,7,6,5,8}, i, j;

    // insert sort
    insert_sort(a, 0, 8);

    // print a[] after sort
    for(i = 0; i < 8; i++){
        cout << a[i] << " ";
    }

    system("pause");
    return 0;
}

// insert sort
void insert_sort(int *a, int left, int right)
{
    int i, j, iTag;

    // put min to the front
    for(i = right - 1; i >= left; i--){
        if (a[i - 1] > a[i]){
            exch(a[i - 1], a[i]);
        }
    }

    // compare and exchange
    for (i = left + 1; i < right; i++){
        j = i;
        iTag = a[j];
        if(a[j - 1] > a[j]){
            a[j] = a[j - 1];
            j --;
        }
        a[j] = iTag;
    }
}

// change two integers
void exch(int &e1, int &e2)
{
    int tmp;
    tmp = e1;
    e1 = e2;
    e2 = tmp;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值