Sorting algorithms 2 - Selection sort

Selection sort is also like bubble sort. It uses another different approach for sorting comparing to bubble sort. But when it comes to sort large volumes of data it is inefficient yet good,easy,adaptive for small volume of data.


Process

  • Lets say we want to sort an unsorted array in ascending order. Meaning largest data on right hand corner.
  • Lest select in th element as the minimum
  • Now from in+1 th element to out element I'm searching a value that is lower than the selected minimum value.
  • If I found a such value that means there is a minimum value than our selected minimum value.
  • So I will swap the initially selected minimum and newly found minimum,
  • Now the minimum is on the left.
  • Now we can worry about the array starting from in+1 to out.
  • Select minimum as in+1 and repeat the above procedure until in gets to out.

 // Selection sort implementation
  public int[] selectionSort(int[] array)
  {
   
   int out = array.length - 1;
   for (int in = 0; in < out; in++) {
   
    int min = in;
    
    for (int j = in+1; j < out + 1; j++) {
    
     if (array[min] > array[j]) {
      
      min = j;
    }
   }
    
    int temp = array[in];
    array[in] = array[min];
    array[min] = temp;
  }
   
   return array;
  }
Share:

0 comments: