Friday, October 16, 2015

Selection Sort Comparable Array Items in Java

Selection sort is one of the in-place sorting algorithms.

It is considered simple to implement but not efficient for large inputs.

General steps :

1-) Start from the beginning index
2-) Find the minimum
3-) Swap the found minimum with the item at the starting position of the set
4-) Do it until the last item is reached


Space and time complexity values are :

Worst case performance О(n2)
Best case performance О(n2)
Average case performance О(n2)

Worst case space complexity O(n) total, O(1) auxiliary

Following is the Java implementation of the Selection Sort algorithm where the sort method accepts an array of Comparable items as input parameter.



package basics;

public class SelectionSort {

   public static void sort(Comparable[] a) { 
  
    int N = a.length;
  
    for (int i = 0; i < N; i++) { 

        int minIndex = i;
        for (int j = i + 1; j < N; j++)
        if ( a[j].compareTo(a[minIndex])<0 )
             minIndex = j;

        if (minIndex != i) {
            Comparable temp = a[i];
            a[i] = a[minIndex];
            a[minIndex] = temp;
        }
    }
  
  }

  public static void main(String[] args) {
  
    String[] strArr = { "S", "O", "R", "T", "E", "X", "A", "M", "P", "L", "E" };
  
    System.out.println("Before Sort = " );
    for (int i = 0; i < strArr.length; i++)
     System.out.print(strArr[i] + " ");
    System.out.println("\n");
  
    sort(strArr);
  
    System.out.println("After Sort = " );
    for (int i = 0; i < strArr.length; i++)
     System.out.print(strArr[i] + " ");
    System.out.println();
  
    Integer[] intArr = { 9,8,7,6,6,5,4,3,2,2,1 };
  
    System.out.println();
    System.out.println("Before Sort = " );
    for (int i = 0; i < intArr.length; i++)
     System.out.print(intArr[i] + " ");
    System.out.println("\n");
  
    sort(intArr);
  
    System.out.println("After Sort = " );
    for (int i = 0; i < intArr.length; i++)
     System.out.print(intArr[i] + " ");
    System.out.println();
  }
}



Create a SelectionSort.java file in your workspace.

When the main method inside the SelectionSort class executed it is going to print :

Before Sort =
S O R T E X A M P L E

After Sort =
A E E L M O P R S T X

Before Sort =
9 8 7 6 6 5 4 3 2 2 1

After Sort =
1 2 2 3 4 5 6 6 7 8 9


Because sort method accepts an array or Comparable items, it is safe to send an array of items where each item implements Comparable interface in Java.

No comments:

Post a Comment