码迷,mamicode.com
首页 > 编程语言 > 详细

插入排序

时间:2017-11-20 13:07:05      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:demo   play   ++   blog   ring   initial   end   temp   nts   

/*
*  insertSort.java
*  demonstrates insertion sort
*/
public class ArrayIns {
    //creat array
    private long[] a;
    private int nElems;
    
    //constructor
    public ArrayIns(int max) {
        a = new long[max];
        nElems = 0;
    }
    
    //put elements into array initially
    public void insert(long value) {
        a[nElems] = value;
        nElems++;
    }
    
    //display array
    public void display() {
        for (int j = 0; j < nElems; j++) {
            System.out.print(a[j] + "\t");
        }
        System.out.println("");
    }
    
    //function for insertionSort
    public void insertionSort() {
        int in, out;
        
        for (out = 1; out < nElems; out++) {
            long temp = a[out];
            in = out;
            while(in > 0 && a[in-1] >= temp) {
                a[in] = a[in-1];
                --in;
            }
            a[in] = temp;
        } //end for
    } //end insertionSort
} //end class ArrayIns

public class InsertSortApp {

    public static void main(String[] args) {
        int maxSize = 100;
        ArrayIns arr;
        arr = new ArrayIns(maxSize);
        
        arr.insert(100);
        arr.insert(5);
        arr.insert(55);
        arr.insert(44);
        arr.insert(32);
        arr.insert(87);
        arr.insert(23);
        arr.insert(1);

        arr.display();
        
        arr.insertionSort();
        arr.display();
    } //end main
} //end class InsertSortApp

插入排序

标签:demo   play   ++   blog   ring   initial   end   temp   nts   

原文地址:http://www.cnblogs.com/mmsumz/p/7865405.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!