Java Code for Selection Sort

Java Code for Selection Sort. Selection sort is a sorting algorithm that iteratively finds the minimum/maximum elements in an unsorted sub-array and swaps with the first element. this process repeats until the entire array is sorted.

Selection Sort Algorithm Breakdown

  • Start with the first unsorted element: Consider this element as the minimum for now.
  • Compare the current minimum with the rest of the unsorted elements: If any other element is smaller than the current minimum, update the minimum index.
  • Swap the current minimum with the element it indexes: This places two minimum elements in its correct sorted position.
  • Repeat Steps 2 and 3 for the remaining unsorted array: Increment the sorted position by 1 and repeat the comparison and swapping process for the remaining elements.

Java Program for Selection Sort

Below is a simple Java program that implements the selection sort algorithm to sort an array of integers in ascending order.

Output

Java Program for Selection Sort

Key Points to Remember for the Selection Sort Algorithm

  • In place and not stable: Selection sort is an in-place sorting algorithm. However, it can be made stable with some modifications.
  • Time Complexity: The time complexity of the selection sort algorithm is O(n^2), where n is the number of elements in the array. The time complexity of quick sort makes it inefficient for large datasets.
  • Space Complexity: The selection sort has a space complexity of O(1), which means it requires a constant, small amount of additional storage space.

Selection sorting is particularly useful for small arrays or as an educational tool to learn about sorting algorithms. Its simplicity and the fact that it uses a minimum number of swaps can be advantages in certain scenarios, despite its overall inefficiency compared to more complex algorithms.

Happy Coding & Learning

See Also

3 thoughts on “Java Code for Selection Sort”

Leave a Comment