• 【数据结构与算法】插入排序


    记录一下插入排序。

    public class InsertionSort {
    
        public static void sort(Integer[] array) {
            if (array == null || array.length == 0) {
                return;
            }
    
            Integer value = null;
            Integer tempIndex = null;
            for (int i = 1; i < array.length; i++) {
                value = array[i];
                tempIndex = i - 1;
    
                while (tempIndex >= 0) {
                    if (value < array[tempIndex]) {
                        /* 遍历有序序列,遇到比要插入的元素大的元素,则后移一位 */
                        array[tempIndex + 1] = array[tempIndex];
                        tempIndex--;
                    } else {
                        /* 遍历有序序列,遇到比要插入的元素小的元素,可以停止了 */
                        break;
                    }
                }
    
                array[tempIndex + 1] = value;
            }
        }
    
    }
    import org.junit.Test;
    
    
    public class HowToTest {
    
        @Test
        public void c1() {
            Integer[] array = {3,16,1,5,2,18,0,9,20,11};
            InsertionSort.sort(array);
    
            for (int i = 0; i < array.length; i++) {
                System.out.print(array[i] + ", ");
            }
            System.out.println();
        }
    
        @Test
        public void c2() {
            Integer[] array = {99,98,97,96,95,94,93,92,91,101,90,89,88,87,86,85};
            InsertionSort.sort(array);
    
            for (int i = 0; i < array.length; i++) {
                System.out.print(array[i] + ", ");
            }
            System.out.println();
        }
    
    }
  • 相关阅读:
    阿里图标库引用简介---20200608更新
    2.10排序算法
    2.9Node节点的学习
    2.8DOM节点的学习
    2.5数组
    2.6对象和函数
    2.7变量、内存、Math和Date的初级认识
    css优先级问题
    事件委托(事件代理)初认识
    静态页面学习随笔(1)-如何正确布局大体结构
  • 原文地址:https://www.cnblogs.com/nick-huang/p/5335060.html
Copyright © 2020-2023  润新知