选择排序

AbstractSort请参考排序接口与抽象类(java)

package com.bsc.algorithm.sort.select;

import com.bsc.algorithm.sort.inf.AbstractSort;

/**
 * 选择排序
 * @author bsc
 *
 */
public class SelectSort<T extends Comparable<T>> extends AbstractSort<T> {

    @Override
    /**
     * 找出第1个到最后一个元素中最小值,与第1个交换
     * 找出第2个到最后一个元素中最小值,与第2个交换
     * ...
     * 找出倒数第2个与最后一个元素中最小值,与倒数第2个交换
     */
    protected void sort(T[] data, int cr) {
        int length = data.length;

        for (int i = 0; i < length - 1; i++) {
            //最小值
            T minValue = data[i];
            //最小值数组座标
            int minValueIndex = i;
            for (int j = i + 1; j < length; j++) {
                if (compare(minValue, data[j]) == cr) {
                    //记录最大值或最小值
                    minValue = data[j];
                    //记录最小值数组座标
                    minValueIndex = j;
                }
            }
            if(minValueIndex > i){
                //把最小值和第i个元素交换
                data[minValueIndex] = data[i];
                data[i] = minValue;
            }
        }
    }
}

 测试

ArrayGenerator请参考数组数据生成器

package com.bsc.algorithm.sort.test;

import java.util.Arrays;

import com.bsc.algorithm.data.generator.ArrayGenerator;
import com.bsc.algorithm.sort.heap.HeapSort;
import com.bsc.algorithm.sort.inf.ISort;
import com.bsc.algorithm.sort.select.SelectSort;

public class SortTest {

    public static void main(String[] args) {
        ISort<Integer> sortInt = new SelectSort<Integer>();

        Integer[] dataInt = ArrayGenerator.random(Integer[].class, 10, 0, 99);
        System.out.println("原序:" + Arrays.toString(dataInt));
        sortInt.sortAsc(dataInt);
        System.out.println("升序:" + Arrays.toString(dataInt) + "\n");

        dataInt = ArrayGenerator.random(Integer[].class, 10, 0, 99);
        System.out.println("原序:" + Arrays.toString(dataInt));
        sortInt.sortDesc(dataInt);
        System.out.println("降序:" + Arrays.toString(dataInt) + "\n");

        ISort<Character> sortChar = new SelectSort<Character>();

        Character[] dataChar = ArrayGenerator.random(Character[].class, 10, 65, 90);
        System.out.println("原序:" + Arrays.toString(dataChar));
        sortChar.sortAsc(dataChar);
        System.out.println("升序:" + Arrays.toString(dataChar) + "\n");

        dataChar = ArrayGenerator.random(Character[].class, 10, 65, 90);
        System.out.println("原序:" + Arrays.toString(dataChar));
        sortChar.sortDesc(dataChar);
        System.out.println("降序:" + Arrays.toString(dataChar) + "\n");
    }
}

 

posted @ 2018-06-28 15:33  冰三尺2012  阅读(90)  评论(0编辑  收藏  举报