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

    import com.alibaba.fastjson.JSON;
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * @author: Small sun shine
     * @Description:
     * @date: 2021/6/20 9:40 上午
     */
    @Slf4j
    public class IntSort {
    
        private static int[] source = new int[]{5, 8, 2, 4, 3, 6, 9, 2,2,4,5,6,43,0,87,45};
        private static int totalCount = 0;
        private static int count = 0;
    
        public static void main(String[] args) {
            System.out.println("原始数组数据:" + JSON.toJSONString(check(source)));
            System.out.println("排序后数据:" + JSON.toJSONString(check(source)));
            System.out.println("总交换次数:" + count);
            System.out.println("总比较次数:" + totalCount);
        }
    
        public static int[] check(int[] source) {
            //如果数组为null或长度等于1,就直接返回
            if (null == source || source.length == 1) {
                return source;
            }
            //进行插入排序
            int length = source.length;
            for (int i = 1; i < length; i++) {
                int data = source[i];
                int j = i - 1;
                for (; j >= 0; j--) {
                    totalCount++;
                    if (source[j] > data) {
                        count++;
                        source[j + 1] = source[j];
                    } else {
                        break;
                    }
                }
                source[j + 1] = data;
                String str = String.format("第%d次排序后的次序为:%s", i, JSON.toJSONString(source));
                System.out.println(str);
            }
    
            return source;
        }
    }
    
    缘于生活,而归于工作。本人所书,而意于分享。 如有转载,请注明出处! --活出自己范儿
  • 相关阅读:
    dll-IL-metadata-反射
    Linux(Ubuntu)下安装Angular2
    在nodejs中使用input file批量上传文件的方法
    jq动态添加的元素触发绑定事件无效
    简单的在线计算器
    不同方法实现按钮背景图片的变换
    unity特殊文件夹
    《暗黑战神》随堂笔记
    《打砖块》教程知识梳理
    unity零散小知识
  • 原文地址:https://www.cnblogs.com/Small-sunshine/p/14906191.html
Copyright © 2011-2022 走看看