栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

day43--插入排序

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

day43--插入排序

插入排序:插入排序是简单直接的排序方式之一,将无序序列分成两块,左侧有序,右侧无序,然后将右侧的元素依次插入到左侧合适的位置,使得左侧元素有序。待右侧元素全部插入左侧,整个序列排序完成。
代码:

    public void insertionSort() {
        DataNode tempNode;
        int j;
        for (int i = 2; i 
            tempNode = data[i];
            //Find the position to insert.
            //At the same time,move other nodes.
            for(j = i -1; data[j].key > tempNode.key; j--) {
                data[j + 1] = data[j];
            }// of for j

            //Insert
            data[j + 1] = tempNode;

            System.out.println("Round: " + (i - 1));
            System.out.println(this);
        }// of for i
    }// of insertionSort

    public static void insertionSortTest() {
        int[] tempUnsortedKeys = { -100, 5, 3, 6, 10, 7, 1, 9 };
        String[] tempContents = { "null", "if", "then", "else", "switch", "case", "for", "while" };
        DataArray tempDataArray = new DataArray(tempUnsortedKeys, tempContents);
        System.out.println(tempDataArray);

        tempDataArray.insertionSort();
        System.out.println("Resultrn" + tempDataArray);
    }// of insertionSortTest

运行结果:

------------------------insertionSort-----------------------
I am a data array with 8 item.
(-100,null)  (5,if)  (3,then)  (6,else)  (10,switch)  (7,case)  (1,for)  (9,while)  
Round: 1
I am a data array with 8 item.
(-100,null)  (3,then)  (5,if)  (6,else)  (10,switch)  (7,case)  (1,for)  (9,while)  
Round: 2
I am a data array with 8 item.
(-100,null)  (3,then)  (5,if)  (6,else)  (10,switch)  (7,case)  (1,for)  (9,while)  
Round: 3
I am a data array with 8 item.
(-100,null)  (3,then)  (5,if)  (6,else)  (10,switch)  (7,case)  (1,for)  (9,while)  
Round: 4
I am a data array with 8 item.
(-100,null)  (3,then)  (5,if)  (6,else)  (7,case)  (10,switch)  (1,for)  (9,while)  
Round: 5
I am a data array with 8 item.
(-100,null)  (1,for)  (3,then)  (5,if)  (6,else)  (7,case)  (10,switch)  (9,while)  
Round: 6
I am a data array with 8 item.
(-100,null)  (1,for)  (3,then)  (5,if)  (6,else)  (7,case)  (9,while)  (10,switch)  
Result
I am a data array with 8 item.
(-100,null)  (1,for)  (3,then)  (5,if)  (6,else)  (7,case)  (9,while)  (10,switch)  

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014694.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号