Minimum Swaps 2

  • + 0 comments

    Java 7: Uses Selection sort which guarantees minimum number of swaps.

        static int minimumSwaps(int[] arr) {
            int swaps = 0;
            for(int i = 0; i < arr.length; i++) {
                int minimum = Integer.MAX_VALUE;
                int minimumIndex = -1;
                for(int j = i; j < arr.length; j++) {
                    if (arr[j] < minimum) { 
                        minimum = arr[j];
                        minimumIndex = j; 
                    }
                }
                if (arr[i] != minimum) {
                    int temp = arr[i];
                    arr[i] = arr[minimumIndex];
                    arr[minimumIndex] = temp;
                    swaps += 1;
                }
            }
            return swaps;
        }