python和C语言分别实现插入排序

python语言代码:

ExpandedBlockStart.gif 代码
 1  def  InsertSort(numbers,n):
 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  =  [ 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语言实现代码:

ExpandedBlockStart.gif 代码
#include < stdio.h >

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值