Last Updated: 06 October, 2024 5 Mins
Sorting is the process of arranging a list of unsorted data in a particular order, either ascending or descending. Sort algorithms play a very crucial role for organizing unsorted data and facilitating efficient searching, retrieval, and analysis.
Every sorting algorithm has a unique approach for sorting the data; these sorting algorithms are used according to the specific requirements of the problem, including data size, structure, and distribution, as well as time and space constraints.
In this tutorial, we are going to learn all about Selection Sort in Java.
Selection Sort is a simple and efficient sorting algorithm used to sort a list of unsorted elements in a particular order, either ascending or descending.
In selection sort, the first element in the list is selected, and it is compared repeatedly with all the remaining elements one by one in the list. If any element is smaller than the selected element (for ascending order), then both are swapped so that the first position is filled with the smallest element in the sorted order. Next, we select the element at a second position in the list, and it is compared with all the remaining elements in the list. If any element is smaller than the selected element, then both are swapped. This procedure is repeated until the entire list is sorted.
The following steps are used to carry out the selection sort algorithm:
Step 1: Select the first element of the list.
Step 2: Compare the selected element with all the other elements one by one in the list.
Step 3: In each comparision of elements, if any element is found smaller than the selected element (for Ascending order), then both are swapped.
Step 4: Repeat the same procedure with element in the next position in the list till the entire list is sorted.
A simple Java program of Selection sort is given below for understanding.
Output
BEFORE calling sort method, Array elements:
40 70 90 20 80 100 60 10 30 50
AFTER calling sort method, Array elements:
10 20 30 40 50 60 70 80 90 100
Selection Sort and Bubble Sort are sorting algorithms used to sort an unsorted list of elements; both follow different approaches to sort a list and have many key differences.
In the given table below, summarizing the key differences between both:
Feature | Selection Sort | Bubble Sort |
Approach | Finds the minimum/maximum and swaps | Compares and swaps adjacent elements |
Swaps | Fewer swaps | More frequent swaps |
Efficiency | In terms of swap, more efficient | Less efficient |
Time Complexity | O(n^2) in average and worst cases | O(n^2) in average and worst cases |
Selection sort is the best and most suitable for small datasets, memory-constrained environments (memory usage needs to be minimal), and educational purposes.
That's all, guys. I hope this article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com