Selection Sort is another straightforward sorting algorithm. Its mechanism revolves around dividing the input list into two parts: a sorted and an unsorted region. The algorithm repetitively selects the smallest (or largest, depending on sorting order) element from the unsorted region and places it in the sorted region.
In this post, we'll deep dive into how to implement the Selection Sort algorithm in Java for sorting elements in ascending order. We'll accompany the code with step-by-step explanations to ensure a thorough grasp of the concept.
Java Program for Selection Sort in Ascending Order
public class SelectionSortAscending {
public static void main(String[] args) {
// Initialize a sample array of numbers
int[] numbers = {64, 34, 25, 12, 22, 11, 90};
// Sort the array using Selection Sort
selectionSort(numbers);
// Display the sorted array
System.out.println("Sorted array in ascending order:");
for (int num : numbers) {
System.out.print(num + " ");
}
}
/**
* Perform selection sort on the given array in ascending order.
*
* @param arr The array to be sorted.
*/
public static void selectionSort(int[] arr) {
int n = arr.length;
// One by one move the boundary of the unsorted sub-array
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in the unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the found minimum element with the first element of the sub-array
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
}
Output:
Sorted array in ascending order:
11 12 22 25 34 64 90
Step-by-Step Explanation:
Related Java Programs on Sorting Algorithms
- Bubble Sort in Ascending Order in Java
- Bubble Sort in Descending Order in Java
- Selection Sort in Ascending Order in Java
- Selection Sort in Descending Order in Java
- Insertion Sort in Ascending Order in Java
- Insertion Sort in Descending Order in Java
- Merge Sort in Ascending Order in Java
- Merge Sort in Descending Order in Java
- Quick Sort in Ascending Order in Java
- Quick Sort in Descending Order in Java
Comments
Post a Comment
Leave Comment