选择排序之简单选择排序(java实现)

来源:互联网 发布:oracle删除表数据 编辑:程序博客网 时间:2024/06/14 16:41

在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。
实现代码:

package SelectionSort;/** * Created by root on 3/7/16. */public class SimpleSelectionSort extends RuntimeException{    private int[] sort;    public SimpleSelectionSort(int... sort){        this.sort = sort;    }    /**     *选择排序实现     */    public void sort(){        if(sort.length == 0){            throw new RuntimeException("你没有输入任何参数。。。。");        }else {            for(int i=0;i<sort.length-1;i++){//内部循环主要是为了得到最小的值                int min = sort[i];                int temp ;                for(int j=i;j<sort.length;j++){                    if(min > sort[j]){                        temp = min;                        min = sort[j];                        sort[j] = temp;                    }                }                sort[i] = min;            }        }    }    /**     *     */    public void display(){        if(sort.length == 0){            throw new RuntimeException("您没有输入任何参数。。。");        }else{            for(int i=0;i < sort.length;i++){                System.out.print(sort[i]+"\t");            }        }    }}

测试类:

package SelectionSort;/** * Created by root on 3/7/16. */public class TestSimpleSelectionSort {    public static void main(String[] args) {        SimpleSelectionSort simpleSelectionSort = new SimpleSelectionSort(90,32,65,67,42,45,2,3);        System.out.println("排序前:");        simpleSelectionSort.display();        simpleSelectionSort.sort();        System.out.println("\n排序后:");        simpleSelectionSort.display();    }}

运行后:
运行结果

0 0
原创粉丝点击