`
happy_tao_cool
  • 浏览: 17731 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

选择排序

阅读更多

选择排序的主要思想:在第i趟排序中,将在待排序列中获取最小或者最大的元素与第i个元素交换位置;直到第n-1趟(也就是待排序列的倒数第二个)

 

public class SelectSort {

    private static SortObj[] sortArray = {
        new SortObj(11,""),new SortObj(9,""),new SortObj(18,""),
        new SortObj(77,""),new SortObj(10,""),new SortObj(9,"+"),new SortObj(6,"")};

    public static void sort() {
        
        for(int index = 0;index < sortArray.length - 1;index++) {
            
            // 待插入到有序序列的元素下标
            int selectIndex = index;
            
            // 遍历待排序列,查到最小的元素,记录下标
            for(int indexJ = index + 1;indexJ < sortArray.length;indexJ++) {
                if(sortArray[indexJ].value < sortArray[selectIndex].value) {
                    selectIndex = indexJ;
                }
            }
            exchange(index, selectIndex);
            
            printSortResult();
        }
    }

    
    /**
      * exchange(交换index和selectIndex的元素)
      * @param index
      * @param selectIndex
      */
    private static void exchange(int index, int selectIndex) {
        SortObj obj = sortArray[index];
        sortArray[index] = sortArray[selectIndex];
        sortArray[selectIndex] = obj;
    }
    
    public static void printSortResult() {
        
        for(SortObj obj : sortArray) {
            System.out.print(obj.sequence + obj.value + " ");
        }
        System.out.println();
    }

    /**
      * main(这里用一句话描述这个方法的作用)
      * @param args
      */
    public static void main(String[] args) {
        printSortResult();
        sort();
    }

}

 

public class SortObj {
    // 为了测试方便,将实例变量的作用域置为public
    public int value;
    // 用于标记同一value值的对象先后顺序
    public String sequence;
    
    public SortObj(int value,String sequence) {
        this.value = value;
        this.sequence = sequence;
    }
}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics