zoukankan      html  css  js  c++  java
  • 直接插入排序

    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	",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	",a[i]);
        }
        printf("
    ");
    }
    
    
  • 相关阅读:
    Item2:建造者替代多参数构造器
    Java常量赋值失败?
    0828 列表 增删改查
    字符 列表的切片规则
    0820 字符转换为数字
    使用 in 判断是否有敏感词
    while循环
    for循环
    isalnum 判断变量是否由字符或者数字组成
    使用lower upper等字符大小写指令选择为大小写单词转换大小写
  • 原文地址:https://www.cnblogs.com/yldf/p/6249907.html
Copyright © 2011-2022 走看看