Friday, June 22, 2012

Selection Sort

Iterate in the array and find out the smallest element first replace it with the first element, then iterate the n-1 array and find out smallest element and replace it with 1st element,... Growth of function is n2

package com.webspherenotes.algo;

public class SelectionSort {
 
 public static void main(String[] args) {
  int[] input = {6,5,4,3,2,1};
  
  SelectionSort selectionSort = new SelectionSort();
  selectionSort.printArray(input);
  int[] ouptut = selectionSort.sort(input);
  
  System.out.print("Result is ->");
  selectionSort.printArray(ouptut);
  System.out.println("Number of exchagnes " + selectionSort.noOfExchanges);
 }

 
 private int[] sort(int[] input){
  int length = input.length;
  for(int i = 0 ; i < length -1 ; i++){
   int smallest = i;
   for(int j = i + 1 ; j < length; j++ ){
    if(input[smallest] > input[j]){
     smallest = j;
    }
   }
   if(i != smallest){
    exchange(input, smallest, i);
    printArray(input);
   }
  }
  return input;
 }

 private void printArray(int[] input) {

  System.out.print("{");
  for (int i = 0; i < input.length; i++) {
   System.out.print(input[i]);
   if (i != input.length - 1)
    System.out.print(" , ");
  }
  System.out.println("}");
 }

 int noOfExchanges;

 private void exchange(int[] array, int first, int second) {
  int temp = array[first];
  array[first] = array[second];
  array[second] = temp;
  noOfExchanges++;
 }
}

No comments:

Post a Comment