Skip to main content
JAVA program for selection sort
Selection sort is one of the most basic sorting algorithms in computer science. It sorts an array of elements by comparing all the elements for each position of the array. Selection sort has a time complexity of O(n2).
Approach :
Looping through each position in the array and finding the minimum/maximum element in the array and interchanging the elements.
Algorithm for Selection Sort :
Step-1 : Iterating through each position of the array
Step-2: Setting the element in the current array position as a reference for the minimum/maximum element (depending on ascending/descending order)
Step-3 : Comparing each element and finding the minimum/maximum element in the array (depending on ascending/descending order)
Step-4 : Interchanging the minimum element found with the element in the current array position
Step-5 : Repeating the process throughout the array for each position.
Function Code :
In the above code, we have demonstrated sorting in ascending order. If you want to sort in descending order just change the symbol from '<' to '>' in the line where each value is compared with the minimum value (probably line 19). You may also want to change the name of the variable from 'min' to 'max'.
Sample Output :
Comments
Post a Comment