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;
        }
    }
    
    缘于生活,而归于工作。本人所书,而意于分享。 如有转载,请注明出处! --活出自己范儿
  • 相关阅读:
    二柱子在线答题
    SWUST OJ(952)
    SWUST OJ (943)
    FileZilla 客户端连接 FlieZilla 服务器 连接成功读取目录列表却失败的解决办法
    串的模式匹配算法 ------ KMP算法
    lvalue require as increment operand
    c 语言连续输入字符型数据
    [pat]数素数
    [PAT]数字分类
    HDOJ_4540_威威猫系列故事——打地鼠
  • 原文地址:https://www.cnblogs.com/Small-sunshine/p/14906191.html
Copyright © 2011-2022 走看看