Selection Sort using Recursion in Java

Recursion means a method; calling directly or indirectly themselves. Recursion is a useful programming technique. In some cases, it enables you to develop a straightforward and simple solution to an otherwise difficult problem. This post introduces you how to sort a list using Selection Sort by Recursion in Java. 

Lets calculate the Selection Sort using recursion: 

What is Selection Sort?
 
Selection Sort finds the smallest  number in the list and places it first. It then finds the smallest number remaining and places it after the first, and so on until the remaining list contains only a single number. The problem can be divided into two sub-problems:
  • Find the smallest number in the list and swap it with the first number.
  • Ignore the first number and sort the remaining smaller list recursively. 

SelectionSortRecursive.java


public class SelectionSortRecursive {
      
       public static void main(String [] args){
              double[] sortingList = {9,5,3,7,4,8,6};
             
              sort(sortingList);
             
              // recursion completed now print sorted array
              for (int i=0; i<sortingList.length; i++)
                     System.out.println("sorted list is : " +sortingList[i]);
       }

       public static void sort(double[] list) {
              sort(list, 0, list.length - 1);
             
       }
   
       public static void sort(double[] list, int low, int high) {
              if (low < high) {
                     int indexOfMin = low;
                     double min = list[low];
                     for (int i = low + 1; i <= high; i++) {
                           if (list[i] < min) {
                                  min = list[i];
                                  indexOfMin = i;
                           }
                     }

                     // Swap the smallest number in list
                     list[indexOfMin] = list[low];
                     list[low] = min;

                     // Sort the remaining list
                     sort(list, low + 1, high);

              }
       }
}


Output of the above code listing would look like:
   sorted list is :

   3.0 4.0 5.0 6.0 7.0 8.0 9.0   


No comments:

Post a Comment