选择排序

选择排序

public class TestSort {
    public static void selectSort(int[] a) {
        int index, temp;
        for (int i = 0; i < a.length - 1; i++) {
            index = i;
            for (int j = i + 1; j < a.length; j++) {
                if (a[j] < a[index]) {
                    index = j;
                }
            }
            if (i != index) {
                temp = a[i];
                a[i] = a[index];
                a[index] = temp;
            }
        }
    }
}
import java.util.Arrays;

public class SelectionSort {
    public static void main(String[] args) {
        int[] a = {1, 7, 3, 9, 2, 5, 8, 4, 6, 0};
        selectionSort(a);
        System.out.println(Arrays.toString(a));
    }

    public static void selectionSort(int[] a) {
        int length = a.length;
        int index, temp;
        for (int i = 0; i < length - 1; i++) {
            index = i;
            for (int j = i + 1; j < length; j++) {
                if (a[j] < a[index]) {
                    index = j;
                }
            }
            if (index != i) {
                temp = a[i];
                a[i] = a[index];
                a[index] = temp;
            }
        }
    }
}

原文地址:https://www.cnblogs.com/hgnulb/p/11370949.html