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

    扑克牌,相信很多人都玩过,我们抓牌的时候,一般都是把抓上来的牌跟手上的牌比较,然后插到左边或者右边( 看你是从大到小,还是从小到大 )。

    这就是插入排序。

    package com.ghostwu;
    
    import java.util.Random;
    
    class MyInsertSort{
        int maxSize;
        int[] arr;
        public MyInsertSort( int s ){
            arr = new int[s];
            Random rand = new Random();
            for( int i = 0; i < arr.length; i++ ){
                arr[i] = rand.nextInt( 101 );
            }
        }
        public void sort(){
            //从下标1开始,下标为0就一个数,他就是有序的
            for( int i = 1; i < arr.length; i++ ){
                int tmp = arr[i];
                int j = i;
                //从已经排好序的数 最右边的开始比较,如果小,就把当前的值,继续和他前面的比较
                while( j > 0 && tmp < arr[j-1] ) {                
                    arr[j] = arr[j-1];  //往后移动
                    j--;
                }
                //开始插入
                arr[j] = tmp;
                System.out.println( "第" + i + "轮,排序结果" );
                printArray();
            }
        }
        public void printArray(){
            for( int i = 0; i < arr.length; i++ ){
                System.out.print( arr[i] + "	" );
            } 
            System.out.println();
        }
    }
    
    public class InsertSort2 {
    
        public static void main(String[] args) {
    
            MyInsertSort s = new MyInsertSort( 10 );
            System.out.println( "--------------排序前--------------" );
            s.printArray();        
            s.sort();
            System.out.println( "--------------排序后--------------" );
            s.printArray();
        }
    
    }

    排序细节与结果:

    --------------排序前--------------
    37    87    4    32    9    62    81    41    84    41    
    第1轮,排序结果
    37    87    4    32    9    62    81    41    84    41    
    第2轮,排序结果
    4    37    87    32    9    62    81    41    84    41    
    第3轮,排序结果
    4    32    37    87    9    62    81    41    84    41    
    第4轮,排序结果
    4    9    32    37    87    62    81    41    84    41    
    第5轮,排序结果
    4    9    32    37    62    87    81    41    84    41    
    第6轮,排序结果
    4    9    32    37    62    81    87    41    84    41    
    第7轮,排序结果
    4    9    32    37    41    62    81    87    84    41    
    第8轮,排序结果
    4    9    32    37    41    62    81    84    87    41    
    第9轮,排序结果
    4    9    32    37    41    41    62    81    84    87    
    --------------排序后--------------
    4    9    32    37    41    41    62    81    84    87    
  • 相关阅读:
    JS 跳转
    js 注意问题
    MySql 引擎
    openflashchart 与 FusionCharts 开发中使用
    MySql 字符串连接
    js 颜色选择器
    c#,winform,combobox联动 Virus
    c#,winform,验证输入内容,文本框,长度,errorprovider组件,方便,快捷 Virus
    c#,NHibernate,ASP.NET2.0,Winform Virus
    c#,小发现,关于程序当前目录的问题,Environment.CurrentDirectory,Application.StartupPath; Virus
  • 原文地址:https://www.cnblogs.com/ghostwu/p/9286552.html
Copyright © 2011-2022 走看看