[算法训练营] insertion sort

问题描述

用数组的方式实现插入排序。

输入

待排序数字序列的个数,以及待排序的数字序列。

输出

已排序的数字序列。

样例输入

10

1 5 4 2 3 9 8 7 2 0

样例输出

0
1
2
2
3
4
5
7
8
9

代码

#include <iostream>
#include <stack>
#include <vector>
using std::cin;
using std::cout;
using std::endl;
using std::stack;
using std::vector;

const int maxn = 1e5;

void sorting(int a[], int n);

int main()
{
    int n;
    int seq[maxn];
    cin >> n;
    for (int i = 0; i < n; i++) {
        int tmp;
        cin >> tmp;
        seq[i] = tmp;
    }
    sorting(seq, n);
    for (int i = 0; i < n; i++)
        cout << seq[i] << endl;
    return 0;
}

void sorting(int a[], int n)
{
    if (a == NULL || n <= 1) // 边界情况
        return;

    int i, j, tmp;

    for (i = 1; i < n; i++) {
        tmp = a[i]; // 当前待插入的元素
        for (j = i - 1; j >= 0; j--) { // 寻找tmp插入的位置
            if (a[j] > tmp)
                a[j+1] = a[j];
            else
                break;
        }
        a[j+1] = tmp; // 插入
    }
}

猜你喜欢

转载自www.cnblogs.com/trav/p/10363141.html