python语言代码:
2 for i in range( 1 ,n):
3 j = i - 1
4 tem = numbers[i]
5 while numbers[j] > tem and j >= 0:
6 numbers[j + 1 ] = numbers[j]
7 j -= 1
8 else :
9 numbers[j + 1 ] = tem
10 print " Onthe sort: " ,numbers
11
12 a = [ 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 ,0]
13 print " BeforeSort: " ,a
14 InsertSort(a, 10 )
15 print " After Sort: " ,a
最后输出为:
BeforeSort: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
Onthe sort: [8, 9, 7, 6, 5, 4, 3, 2, 1, 0]
Onthe sort: [7, 8, 9, 6, 5, 4, 3, 2, 1, 0]
Onthe sort: [6, 7, 8, 9, 5, 4, 3, 2, 1, 0]
Onthe sort: [5, 6, 7, 8, 9, 4, 3, 2, 1, 0]
Onthe sort: [4, 5, 6, 7, 8, 9, 3, 2, 1, 0]
Onthe sort: [3, 4, 5, 6, 7, 8, 9, 2, 1, 0]
Onthe sort: [2, 3, 4, 5, 6, 7, 8, 9, 1, 0]
Onthe sort: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
Onthe sort: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
After Sort: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
C语言实现代码:
void insertSort( int a[ 10 ], int n)
{
int i,j,k;
for (i = 1 ;i < n;i ++ )
{
int tem = a[i];
j = i - 1 ;
while (a[j] > tem && j >= 0 )
{
a[j + 1 ] = a[j];
j -- ;
}
a[j + 1 ] = tem;
for (k = 0 ;k < 10 ;k ++ )
{
printf( " %d " ,a[k]);
}
printf( " \n " );
}
}
int main()
{
int b[ 10 ] = { 9 , 8 , 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 };
int i;
for (i = 0 ;i < 10 ;i ++ )
{
printf( " %d " ,b[i]);
}
printf( " \n " );
insertSort(b, 10 );
for (i = 0 ;i < 10 ;i ++ )
{
printf( " %d " ,b[i]);
}
}
最后输出:
9876543210
8976543210
7896543210
6789543210
5678943210
4567893210
3456789210
2345678910
1234567890
0123456789