Learn the basics of the Selection Algorithm with explanations and examples.
A selection algorithm is used to select the kth smallest (or largest) element from an unsorted collection of elements. The most common example of a selection algorithm is finding the minimum or maximum value in an array.
The selection algorithm is used to find the minimum (or maximum) value from an unsorted list by repeatedly selecting the smallest (or largest) element.
Below is an implementation of the Selection Sort algorithm, which is a selection algorithm used to sort an array by selecting the smallest element and placing it at the correct position:
// Java Code: Selection Sort
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Original Array:");
printArray(arr);
for (int i = 0; i < arr.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
System.out.println("\nSorted Array:");
printArray(arr);
}
// Helper function to print the array
static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
}
Original Array:
64 25 12 22 11
Sorted Array:
11 12 22 25 64
Consider the process of finding the shortest path in a navigation system. The selection algorithm can be used to choose the shortest route from a set of possible paths, evaluating each option to find the optimal one.
Selection algorithms are widely used in various applications, such as:
For a deeper understanding of selection algorithms, check out these helpful videos: