算法导论学习(2.1)-插入排序及c++实现

插入排序伪代码:循环不定式的定义: 

插入排序的循环不变式:

插入排序c++实现(正序)

#include<iostream>
using namespace std;
void Display(int array[],int length);
void InsertionSort(int array[],int length);
int main()
{  
    int a[10]={56,1,3,7,9,514,70,8,81,10};
    Display(a,10);
    cout<<endl<<"使用插入排序后";
    InsertionSort(a,10);
    Display(a,10);
    system("pause");
    return 0;
}
void Display(int array[],int length)
{
    for(int a=0;a<length;a++)
    {        
        cout<<"这是数组的第 "<<a<<"个元素:"<<array[a]<<endl;
    }
}
void InsertionSort(int array[],int length)
{
    for(int j=1;j<length;j++)
    {
        int key=array[j];
        int i=j-1;
        while(i>=0&&array[i]>key)
        {
            array[i+1]=array[i];
            i--;
        }
        array[i+1]=key;
    }
}

倒序:

#include<iostream>
using namespace std;
void Display(int array[],int length);
void InsertionSortDown(int array[],int length);
int main()
{  
    int a[10]={56,1,3,7,9,514,70,8,81,10};
    Display(a,10);
    cout<<endl<<"数组排序后的结果为";
    InsertionSortDown(a,10);
    Display(a,10);
    system("pause");
    return 0;
}
void Display(int array[],int length)
{
    for(int a=0;a<length;a++)
    {        
        cout<<"这是数组的第 "<<a<<"个元素:"<<array[a]<<endl;
    }
}
void InsertionSortDown(int array[],int length)
{
    for(int j=1;j<length;j++)
    {
        int key=array[j];
        int i=j-1;
        while(i>=0&&array[i]<key)
        {
            array[i+1]=array[i];
            i--;
        }
        array[i+1]=key;
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值