public class SelectionSortExample
{
public static void main(String[] args)
{
int[] arr = {49, 74, 25, 36, 88, 18, 31};
int n = arr.length;
// Selection Sort Algorithm
for (int i = 0; i < n - 1; i++)
{
int minIndex = i;
// Find the minimum element in unsorted part
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;
}
// Print sorted array
System.out.print("Sorted Array: ");
for (int num : arr)
{
System.out.print(num + " ");
}
}
}
Sorted Array: 18 25 31 36 49 74 88
Case | Description | No. of Comparisons | Time Complexity |
---|---|---|---|
Worst Case | Array is in reverse order; all comparisons still required. | n(n-1)/2 |
O(n²) |
Average Case | Elements are in random order; all comparisons still required. | n(n-1)/2 |
Θ(n²) |
Best Case | Array is already sorted; comparisons still performed, but minimum swaps. | n(n-1)/2 |
Ω(n²) |
O(1)
→ only a few variables used; no extra memory needed.
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
We’re here to make our tutorials better based on your thoughts and suggestions.