冒泡排序和插入排序

本文介绍了一种使用C++模板实现的排序算法,包括冒泡排序和插入排序,并提供了一个简单的打印数组函数用于验证排序结果。通过一个整数数组的例子展示了如何调用这些排序函数。

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

#include <iostream>
using namespace std;
template <typename T>
//冒泡排序
int bubbleSort(T *const t, int len)
{
    for(int i = len - 1; i > 0; i--)
    {    
    for(int j = 0 ; j < i; j++)
        {
        if(t[j] > t[j + 1])
        {
            T temp = t[j];
        t[j] = t[j + 1];
        t[j + 1] = temp;
        }
    }
    }
    return 0;
}
//插入排序
template <typename T>
int insertSort(T *const t, int len)
{
    for(int i = 1; i < len; i++)
    {
    for(int j = i; j >= 1; j--)
        {
        if(t[j] < t[j - 1])
        {
            T temp = t[j - 1];
        t[j - 1] = t[j];
        t[j] = temp;
        }else
        {
        break;
        }
    }
    } 
}
template <typename T>
int printArray(T *const t, int len)
{
    for(int i = 0; i < len; i++)
    {
    cout << t[i] << ';';
    }
    cout<<endl;
}
int main(int argc, char *argv[])
{
    int c[10] = {9,4,7,6,11,4,3,2,1,0};
   // bubbleSort(c, sizeof(c)/sizeof(int));
    insertSort(c, sizeof(c)/sizeof(int));
    printArray(c, sizeof(c)/sizeof(int));
    return 0;    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值