select sort int array - Java java.lang

Java examples for java.lang:int Array

Description

select sort int array

Demo Code



public class Main{
    public static void main(String[] argv) throws Exception{
        int[] arr = new int[]{34,35,36,37,37,37,67,68,69};
        System.out.println(java.util.Arrays.toString(selectSort(arr)));
    }/*from   ww w .  j  a v a 2 s .  c  o m*/
    /**
     * select sort
     */
    public static int[] selectSort(int[] arr) {
        int swapCount = 0;
        for (int i = 0; i < arr.length; i++) {
            int temp = i;
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[j] < arr[temp]) {
                    temp = j;
                }
            }
            if (temp != i) {
                ArrayUtil.swap(arr, temp, i);
                swapCount++;
            }
        }
        System.out.println("swap count(select sort): " + swapCount);
        return arr;
    }
    /**
     * swap two element in array
     */
    private static int[] swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
        return arr;
    }
}

Related Tutorials