Implements a Selection sort - Java Data Structure

Java examples for Data Structure:Sort

Description

Implements a Selection sort

Demo Code



public class Selection {

    public static void sort(Comparable[] a) {
        int N = a.length;
        for (int i = 0; i < N; i++) {
            int min = i;
      //from   w w  w .  j  a  va 2  s.co m
            for (int j = i+1; j < N; j++) {
                if (less(a[j], a[min]))
                    min = j;
            }
            exch(a, i, min);
        }
    }
    
    //check if the first argument is smaller than second
    private static boolean less(Comparable v, Comparable w) {
        return v.compareTo(w) < 0;
    }
    
    //swap elements (i by j)
    private static void exch(Comparable[] a, int i, int j) {
        Comparable swap = a[i];
        a[i] = a[j];
        a[j] = swap;
    }
    
    public static void main(String[] args) {
        Integer[] data = new Integer[] {28, 96, 51, 86, 69, 68, 42, 24, 52, 27};
        sort(data);
        
        System.out.print("Array sorted by Selecion sort: ");
        for (Integer x: data) {
            System.out.printf("%s ",x);
        }
    }

}

Related Tutorials