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

    直接插入:就是把未排序的数据插入到已排序的数列中去

    步骤:从排序数组的第二个数开始,依次与前面的数比较,比前面的数大的话就插入到前面去,依次循环完。

        public static void sort(int a[]){
            
            //key用来保存待插入的值,index用来指示已排序的数组下标
            int key,index; 
            
            for(int i = 1 ; i < a.length; i++){
                
                key = a[i];
                for(index = i -1; index >= 0 &&a[index] < key; index--){
                    a[index+1] = a[index];
                }
                a[index+1] = key;
            }
        }

    完整代码:

    package sort;
    
    /**
     * 直接插入排序
     *
     * @author lin
     *
     */
    public class Select {
    
        static int a[] = {5,3,6,7,3,2,9,6,3,6};
        
        public static void main(String[] args) {
            sort(a);
            print(a);
        }
            
        public static void sort(int a[]){
            
            //key用来保存待插入的值,index用来指示已排序的数组下标
            int key,index; 
            
            for(int i = 1 ; i < a.length; i++){
                
                key = a[i];
                for(index = i -1; index >= 0 &&a[index] < key; index--){
                    a[index+1] = a[index];
                }
                a[index+1] = key;
            }
        }
        
        public static void  print(int a[]){
            for(int i = 0; i < a.length; i ++)
            System.out.format("%d ", a[i]);
        }
    }
  • 相关阅读:
    多线程常见面试题
    Redis常见面试题总结
    ehcache缓存技术的特性
    sar 命令详解
    面试题
    BOOTPROTO=[none|static|bootp|dhcp](引导时不使用协议|静态分配|BOOTP协议|DHCP协议)
    课后习题-10
    ulimit 命令详解
    课后习题-9
    netstat 命令详解
  • 原文地址:https://www.cnblogs.com/mynona/p/3606200.html
Copyright © 2011-2022 走看看