1. 程式人生 > >排序算法: 插入排序

排序算法: 插入排序

時間復雜度 插入 插入排序 移動 urn 元素 highlight light space

算法分析

(1)時間復雜度

從時間來看,排序的基本操作為:比教兩個關鍵字的大小移動記錄。

#include<iostream>
#include<vector>
using namespace std;
void InsertSort(int a[], int n)
{
	for (int i = 1; i < n; i++)
	{
		if (a[i] < a[i - 1])//如果小於已經排好序的最後一個元素,則需要把元素插入
			//已經排好序的序列中,否則就不需要移動
		{
			int key = a[i];
			//a[i] = a[i - 1];
			int j = i - 1;
			for (; key < a[j]; j--)
			{
				a[j + 1] = a[j];
			}
			a[j + 1] = key;
		}
	}
}
int main()
{
	int a [11] = { 2,6,4,5,54,53,53,5,34,34,32};
	InsertSort(a, 11);
	for (int i = 0; i < 11; i++)
	{
		cout << a[i] << " ";
	}
	return 0;
}

  

排序算法: 插入排序