您的位置:首页 > 其它

直接插入排序

2016-04-27 20:42 281 查看

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");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: