
Selection Sort is a simple but inefficient sorting algorithm. It works by repeatedly finding the smallest (or largest) element in the unsorted portion of the array and swapping it with the first element of the unsorted portion.
import java.util.Arrays;
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
// Loop through all array elements
for (int i = 0; i < n - 1; i++) {
// Find the minimum element in the unsorted part
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("Original Array: " + Arrays.toString(arr));
selectionSort(arr);
System.out.println("Sorted Array: " + Arrays.toString(arr));
}
}
def selection_sort(arr):
n = len(arr)
for i in range(n):
# Find the index of the smallest element in the unsorted part
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
# Swap the smallest element with the first element of the unsorted part
arr[i], arr[min_index] = arr[min_index], arr[i]
# Example usage
if __name__ == "__main__":
arr = [64, 25, 12, 22, 11]
print("Original Array:", arr)
selection_sort(arr)
print("Sorted Array:", arr)
Selection Sort is useful in scenarios where:
Although Selection Sort is simple and educational, it is rarely used in practical applications due to its inefficiency. For better performance, algorithms like Merge Sort or Quick Sort are preferred.
When analyzing a stock, one of the first financial indicators you’ll encounter is EPS, or Earnings Per Share. It’s one… Read More
When you look at a stock’s profile on a financial website, one of the first things you’ll see is its… Read More
In the world of open-source software, simplicity and flexibility are often just as important as legal protection. That’s why the… Read More
If you want your software to be open source, but still compatible with commercial use—and not as restrictive as the… Read More
When it comes to open-source software, developers and businesses alike need licenses that balance freedom, legal clarity, and long-term security.… Read More
If you’re working on open-source projects or choosing third-party libraries for your software, understanding software licenses is essential. Among the… Read More