码迷,mamicode.com
首页 > 其他好文 > 详细

SelectSort

时间:2017-11-17 23:26:28      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:tap   arrays   div   string   min   code   struct   rgs   stat   

/*
* 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();
    }
}

SelectSort

标签:tap   arrays   div   string   min   code   struct   rgs   stat   

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

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