每日一练--直接插入排序

现在找工作的压力这么大,为了以后好找工作,现在开始要多看看算法,所以以后可以每天做个小题目,练习一下。今天作为第一天,说个最简单的直接插入排序。
直接插入排序可以这么理解,把A[j]和A[0]….A[j-1]的数进行比较,如果比他们小,就插入到比它小的前一位,直接插入排序的时间复杂度是O(n^2).
先给出伪代码分析

//the index of array is from 0
for j=1 to num.length
    key = num[j];
    i = j-1;
    while i >= 0 and num[i] > key
    {
        num[i+1] = num[i];
        i--;
    }
    num[i+1] = key;

下面用c++来实现

// insertsort.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<stdlib.h>
using namespace std;

int main()
{
    int num[10] = {10,20,1,78,34,99,12,21,2,55};
    int key;
    cout << "the number has not been sorted:" << endl;
    for (int i = 0;i < 10;i++)
    {
        cout << num[i] << ' ';
    }
    cout << endl;
    cout << "the number has been sorted:" << endl;
    for (int j =1;j <10;j++)
    {
        int key = num[j];
        int i = j-1;
        while(i >=0&&num[i]>key)
        {
            num[i+1] = num[i];
            i--;
        }
        num[i+1] = key;
    }

    for (int m = 0;m < 10;m++)
    {
        cout << num[m] << ' ';
    }
    cout << endl;
    return 0;
}

今天一练,到此结束。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值