Logic Building: Selection Sort in Apex

The selection sort algorithm sorts a list by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.

In sorting algorithm list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.

The smallest element is selected from the unsorted list and swapped with the leftmost element, and that element becomes a part of the sorted list

The algorithm maintains two sublist in a given list.

1) The sublist which is already sorted.
2) Remaining sublist which is unsorted.

Example: Sort the list [10,5,65,30,40]

1.Set MIN to location 0
2.Search the minimum element in the list
3.Swap with value at location MIN
4.Increment MIN to point to next element
5.Repeat until the list is sorted

SelectionSort.apxc

public class SelectionSort
{
    public static void selectionSorting(list<integer> sortlist)
    {
         integer len = sortlist.size();
 
        for (integer i = 0; i < len-1; i++)
        {
           // Finding the minimum element in the unsorted part of array
            integer min = i;
            for (integer j = i+1; j < len; j++)
                if (sortlist[j] < sortlist[min])
                    min = j;
 
            /* Swapping the found minimum element with the first
             * element of the sorted subarray using temp variable
             */
            integer temp = sortlist[min];
            sortlist[min] = sortlist[i];
            sortlist[i] = temp;
        
        }
    
}
}

Anonymous Window

 list<integer> numval = new list<integer>{10,5,65,30,40};  
        SelectionSort.selectionSorting(numval);  
system.debug(numval);

Output

Did you enjoy this article?
Signup today and receive free updates straight in your inbox.
I agree to have my personal information transfered to MailChimp ( more information )
50% LikesVS
50% Dislikes