• 插入排序


    例如:一个序列:{20,40,30,10,60,50}

    1.首先第一趟,将第一个序列中第一个元素保留,将第二个元素和它比较,如果大就插入到后面,如果小就插入到前面。 

     

    2.第二趟,保留第一第二个元素,将第三个元素和第二个比较,如果大就插入到第二个元素后面,如果小就插入到第二个元素前面;

     接着和第一个元素比较,如果大就插入到第一个元素后面,如果小就插入到第一个元素前面。 

     

    3. 第三趟以及其他趟如上

     代码演示:

    /**
     * 插入排序  (默认第一个数已经排序好,后面每个数与已经排序的数字从后到前比较)
     * @author Administrator
     *
     */
    public class TestArray {
    
        public static void main(String[] args) {
            int [] arr = {9,5,8,4,1,3,5,7,2}; 
            int i, j, temp ;
            for (i = 1; i < arr.length; i++) {
                    temp = arr[i];
                for (j = i - 1; j >=0; j--) {
                    if (temp > arr[j]) {
                        break;
                    }else {
                        arr[j + 1] = arr[j];
                        //arr[j] =temp;  //没比较一次就插入一次
                    }
                }
                arr[j + 1] = temp;   //比较完之后再插入
            }
            printArr(arr);    
        }
        public static void printArr(int[] arr) {
            for (int i = 0; i < arr.length; i++) {
                System.out.println(arr[i]);
            }
        }
    }
  • 相关阅读:
    透明数据加密 (TDE)常见问题解答
    oracle wallet使用与维护
    Mybatis 一对一、一对多、多对一
    Mybatis-Plus
    eclipse安装spring boot插件spring tool suite
    springboot在idea实现热部署
    springboot在eclipse实现热部署
    SpringBoot配置文件-application.properties详解
    Dubbo入门
    Shell入门
  • 原文地址:https://www.cnblogs.com/sacai/p/11590639.html
Copyright © 2020-2023  润新知