Inserting Sort C++

Since an array with one element is a sorted array. By insert second element into this one array, we get a sorted array of size 2, Continuing in this way, we obtain a sorted array of size n.  
// InsertionSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

using namespace std;

template <class T>
void PrintfNum(T a[], int n);

template <class T>
void InsertionSort(T a[], int n){
    for (int i = 1; i < n; i++) {
    T t = a[i];
    int j;
    for (j = i-1; j >= 0 && t < a[j]; j--)
      a[j+1] = a[j];
      a[j+1] = t;
	  PrintfNum(a,4);
	}

}

int main(int argc, char* argv[])
{
	int a[4]={4,3,2,1};
	cout << "Before sort:" << endl;
    PrintfNum(a,4);

	cout << "Insertion Sort :" << endl;
	InsertionSort(a, 4);
	return 0;
}

template <class T>
void PrintfNum(T a[], int n){
	for(int i = 0; i < n; i++){
		cout << a[i] << ",";
	}
	cout << endl;
}
An example , There is a array 4, 3, 2, 1   First element is 4, it is a sorted array of size 1.   The second element 3 is smaller than 4, so set 4 one more position to the right. So the array changed to 3, 4, 2, 1. The 3, 4 is a sorted array of size 2.   The third element 2 is smaller than 3, so set 3 and 4 one more position to the right. So the array changed to 2, 3, 4, 1. The 2, 3, 4 is a sorted array of size 3. The fourth element 1 is smaller than 2, so set2, 3 and 4 one more position to the right. So the array changed to 1,2, 3, 4, Done. http://www.easycpp.com/?p=7

转载于:https://www.cnblogs.com/easycpp/p/3403522.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值