This generic method sorts the input array using a selection sort and the input Comparator object. - Java Collection Framework

Java examples for Collection Framework:Array Sort

Description

This generic method sorts the input array using a selection sort and the input Comparator object.

Demo Code


//package com.java2s;

import java.util.Comparator;

public class Main {
    /**/*from w ww  .  ja v a 2s.c  o m*/
     * This generic method sorts the input array using a selection sort and the input Comparator object.
     * @param arr
     * @param c
     */
    public static <T> void selectionSort(T[] arr, Comparator<? super T> c) {
        // validate parameters
        if (arr == null) {
            throw new IllegalArgumentException(
                    "The given array cannot be null!");
        }
        if (c == null) {
            throw new IllegalArgumentException(
                    "The given comparator cannot be null!");
        }

        int smallestIndex;
        for (int i = 0; i < arr.length - 1; i++) {
            smallestIndex = i;

            // Find the index of the smallest element
            for (int j = i + 1; j < arr.length; j++) {
                if (c.compare(arr[j], arr[smallestIndex]) < 0) {
                    smallestIndex = j;
                }
            }

            // Swap elements if necessary
            if (smallestIndex != i) {
                T temp = arr[i];
                arr[i] = arr[smallestIndex];
                arr[smallestIndex] = temp;
            }
        }
    }
}

Related Tutorials