选择排序

/*
* selectSort.java
* demonstrates selection sort
* use long[] a for example
*/

public class ArraySel {
    //ref array
    private long[] a;
    private int nElems;

//    ---------------------
    //constructor
    public ArraySel(int max) {
        //creat an array
        a = new long[max];
        nElems = 0;
    }
//    -----------------------
    //insert element into array
    public void insert(long value) {
        a[nElems] = value;
        nElems++;
    }
//    ----------------------
    //display array contents
    public void display() {
        for (int j = 0; j < nElems-1; j++) {
            System.out.print(a[j] + "\t");
        }
        System.out.println("");
    }
//    ---------------------
    public void selectionSort() {
        int out, in, min;

        for (out = 0; out < nElems-1; out++) {
            min = out;
            for (in = out+1; in < nElems; in++) {
                if (a[in] < a[min]) {
                    min = in;
                }
                swap(out, min);
            }
        }
    }
//    --------------------------------
    public void swap(int one, int two) {
        long temp;
        temp = a[one];
        a[one] = a[two];
        a[two] = temp;
    }
}
//end class ArraySel

public class SelectSortApp {
    public static void main(String[] args) {
        int maxsize = 100;
        ArraySel arr;
        arr = new ArraySel(maxsize);

        arr.insert(88);
        arr.insert(5);
        arr.insert(66);
        arr.insert(31);
        arr.insert(1);
        arr.insert(98);
        arr.insert(69);

        arr.display();

        arr.selectionSort();
        arr.display();
    }
}
posted @ 2017-11-17 22:33  Mmsumz  阅读(67)  评论(0编辑  收藏  举报