// InsertSort.cpp : Defines the entry point for the console application. // Version:20100731 // Created by Xianyi.Ye #include "stdafx.h" #include <iostream.h> void insertSort(int num[] , int length) { for(int i=2 ; i<length ; i++) // We need to start to sort from num[2], because num[0] is the guard. { // and num[1] is the first sorted value. num[0] = num[i] ; // num[0] is the guard which is the value that will be inserted, num[i] ; int j = i ; while(num[0]<num[j-1]) // We needn't to worry about the ArrayIndex out of bounds, { // because the first number of array is num[0] that equals num[j] = num[j-1] ; // of num[i]. j-- ; } num[j] = num[0] ; } } int main(int argc, char* argv[]) { int num[9] = {-1,49,38,65,97,76,13,27,49} ; // We need to add an additional space for the guard // which is used to store the value that will be inserted. insertSort(num , 9) ; for(int i=1 ; i<9 ; i++) cout<<num[i]<<" " ; cout<<endl ; return 0; }