zoukankan      html  css  js  c++  java
  • 插入排序----一看必会系列

    这是网上的插入排序看着酷炫,吊炸天,但是不太好理解(其实细细品,也还可以)
    for(int i= 1; i< array.length; i++){
    int insertVal = arr[i];
    int insertIndex = i -1;
    while(insertIndex >=0 &&insertvalue<array[insertIndex]){
    array[insertIndex +1] = array[insertIndex];
    insertIndex--;
    }
    if(insertIndex + 1 ==i){
    array[insertIndex + 1] = insertVal;
    }
    }

      

    半小时前打开CSDN看网上有个关于插入排序的东西,然后一看有点稀碎,突然感觉自己不会了于是自己写了一下

    说明:自己看必看懂的东西:

    /**
    * 插入排序基本思想:把N个等待排序 的元素看成一个有序表 和一个无序表

    *开始时有序表只包含一个元素,无序表中含有N-1个元素,排序过程中每次从

    *无序表的排序码进行比较, 将它插入到有序 表达适当位置.

    */

    public class InsertionSort {
        public static void main(String[] args) {
            int[] arry = { 17, 3, 25, 14, 20, 9 };
            ArrayList<Integer> result = InsertionSort(arry);
            for (int value : result) {
                System.out.printf("%d%s", value, " ");
            }
        }
    
        public static ArrayList<Integer> InsertionSort(int[] array) {
            ArrayList<Integer> lists = new ArrayList<>();// 有序表,这个就是有序表
            ArrayList<Integer> lists2 = new ArrayList<>();// 无序表,这个就是无序表
            lists.add(array[0]);
            for (int i = 1; i < array.length; i++) {
                lists2.add(array[i]);
            }
             //这一层循环的意思就是将无序表中的元素添加到有序表中
            for (int i = 0; i < lists2.size(); i++) {
                int value = lists2.get(i);
    //编写一个insert方法将数据一个一个的插入 insert(lists, value); }
    return lists;
    }
    //保姆级insert方法
    public static void insert(ArrayList<Integer> list, int value) {//list 将要插入的有序表,value就是插
    入的元素
    if (list.size() == 1) { if (value > list.get(0)) { list.add(value); } else if (value < list.get(0)) { list.add(0, value); } } else { if (value < list.get(0)) { list.add(0, value); } else if (value > list.get(list.size() - 1)) { list.add(value); } else { for (int i = 0; i < list.size(); i++) { /* * if(value == list.get(i)){ list.add(i+1,value); } else */ if (list.get(i) < value && list.get(i + 1) > value) { list.add(i + 1, value); } } } } }
    }

    恭喜我们都是会插入排序的娃娃了

  • 相关阅读:
    边工作边刷题:70天一遍leetcode: day 11-1
    边工作边刷题:70天一遍leetcode: day 11
    边工作边刷题:70天一遍leetcode: day 12-1
    边工作边刷题:70天一遍leetcode: day 12
    边工作边刷题:70天一遍leetcode: day 13-1
    边工作边刷题:70天一遍leetcode: day 13-2
    边工作边刷题:70天一遍leetcode: day 13
    边工作边刷题:70天一遍leetcode: day 14-1
    边工作边刷题:70天一遍leetcode: day 14
    边工作边刷题:70天一遍leetcode: day 15
  • 原文地址:https://www.cnblogs.com/whr-blogs/p/12685147.html
Copyright © 2011-2022 走看看