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

每天学点java_java选择排序

时间:2015-06-04 13:16:51      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

package com.czj;

public class SelectSort {
    /**
     * 选择排序,对sortArray传入的数组进行从小到大排序。
     * 思路就是   找到数组中最小的值,放到数组第一个位置,然后找到第二个最小值,放到第二个位置
     * @param sortArray
     */
    public void selectSort(int[] sortArray){
        int last=sortArray.length; //last为数组长度
        for(int i=0;i<last;i++){ //遍历循环数组
            int currentMin=sortArray[i];//设定数组第一个为最小值
            int currentMinIndex=i;//记录下标
            
            //找出比设定的最小值更小的值,记录值和下标
            for(int j=i;j<last;j++){
                if(currentMin>sortArray[j]){//这里换成大于号可以让数组从大到小排列
                    currentMin=sortArray[j];
                    currentMinIndex=j;
                }
            }
            //进行交换,把最小的值换到最前面,
            if(currentMinIndex!=i){
                sortArray[currentMinIndex]=sortArray[i];
                sortArray[i]=currentMin;
            }
        }
    }
    
    public static void main(String[] args) {
        int[] sortNum={1,5,2,7,4,9,345,234};
        SelectSort selectSort=new SelectSort();
        selectSort.selectSort(sortNum);
        for(int i:sortNum){
            System.out.print(i+",");
        }
    }
    

}

 

每天学点java_java选择排序

标签:

原文地址:http://www.cnblogs.com/JohnChen-happy/p/4551285.html

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