直接插入排序

java版本

/*************************************************************************
    > File Name: DirectInsertSort.java
    > Author: lxlm
    > Created Time: 2016年04月27日 星期三 20时21分35秒
 ************************************************************************/

public class DirectInsertSort
{
    public static void main(String[] args)
    {
        int[] a={6,1,2,7,9,3,4,5,10,8};
        directInsertSort(a);
        printArray(a);
    }
    public static void directInsertSort(int[] a)
    {
        int temp = 0;
        int n = a.length;
        int j;
        if(n==1 || n==0)
        {
            return;
        }
        for(int  i=1;i<n;i++)
        {
            temp = a[i];
            for(j=i-1;j>=0 && temp<a[j];)//注意:必须将j>=0放在temp<a[j]前面
            {
                a[j+1] = a[j];
                --j;
            }
            a[j+1] = temp;
        }
    }

    public static void printArray(int[] a)
    {   
        for(int item:a)
        {
            System.out.printf("%d\t",item);
        }
        System.out.println();
    }
}

C版本

/*************************************************************************
    > File Name: directInsertSort.c
    > Author: lxm
    > Created Time: 2016年04月27日 星期三 20时10分14秒
 ************************************************************************/

#include<stdio.h>

#define N 10

void directInsertSort(int* a, int n);
void printArray(int* a, int n);
int main(void)
{
    int a[] = {6,1,2,7,9,3,4,5,10,8};
    directInsertSort(a,N);
    printArray(a,N);
    return 0;
}

void directInsertSort(int* a, int n)
{
    int i,j;
    int temp;
    for(i=1;i<n;i++)
    {
        temp = a[i] ;
        for(j=i-1;j>=0 && temp<a[j];)
        {
            a[j+1] =a[j];
            j--;
        }
        a[j+1]=temp ;   
    }
}


void printArray(int* a, int n)
{
    int i;
    for(i=0;i<n;i++)
    {
        printf("%d\t",a[i]);
    }
    printf("\n");
}

转载于:https://www.cnblogs.com/yldf/p/6249907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值