Selection sort is a sorting algorithm that works by repeatedly finding the minimum element from the unsorted part of the list and swapping it with the first element of the unsorted part. This process continues until all elements are sorted in ascending order.
Algorithm:
Start with the first element of the list. This element is considered "sorted" already.
Find the minimum element among the remaining unsorted elements in the list.
Swap the minimum element with the first element of the unsorted part.
Now consider the second element as the first element of the sorted part. Repeat steps 2 and 3 for the remaining unsorted elements.
Continue this process until all elements are sorted, meaning there are no more unsorted elements left.
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
void selection_sort(int arr[], int n) {
// Iterate through each element (except the last)
for (int i = 0; i < n - 1; i++) {
// Find the index of the minimum element in the unsorted part
int min_idx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
// Swap the minimum element with the first element of the unsorted part
swap(&arr[min_idx], &arr[i]);
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
selection_sort(arr, n);
printf("Sorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Here are the steps to visualize the sorting process:
Iteration 1:
Consider the first element (64) as the minimum initially.
Compare 64 with the remaining elements (34, 25, 12, 22, 11, 90).
Find the minimum element (11) and its index (5).
Swap 11 and 64 (array becomes: 11, 34, 25, 12, 22, 64, 90).
Iteration 2:
Consider the second element (34) as the minimum initially (since the first element is already sorted).
Compare 34 with the remaining unsorted elements (25, 12, 22, 64, 90).
Find the minimum element (12) and its index (3).
Swap 12 and 34 (array becomes: 11, 12, 25, 22, 64, 34, 90).
Iteration 3:
Repeat the same process for the remaining elements, considering the next unsorted element as the minimum initially and comparing it with the remaining unsorted elements.
Swap the minimum element with the first element of the unsorted part in each iteration.
Final Iteration:
After n-1 iterations, the entire array will be sorted.
Remember that this is a general visualization, and the specific element comparisons and swaps might differ depending on the initial order of elements in the array. However, the core principle of finding the minimum element and swapping it with the first element of the unsorted part remains the same throughout the sorting process.
Comments