Example with Explanation:
Let’s take the array: [64, 25, 12, 22, 11]
Step-by-Step Execution:
First pass (i=0):
Initial array:
[64, 25, 12, 22, 11]
Find the smallest element from the entire array (from index 1 to 4).
The smallest element is
11
at index 4.Swap
64
and11
.Array after swap:
[11, 25, 12, 22, 64]
Second pass (i=1):
Find the smallest element from
[25, 12, 22, 64]
.The smallest element is
12
at index 2.Swap
25
and12
.Array after swap:
[11, 12, 25, 22, 64]
Third pass (i=2):
Find the smallest element from
[25, 22, 64]
.The smallest element is
22
at index 3.Swap
25
and22
.Array after swap:
[11, 12, 22, 25, 64]
Fourth pass (i=3):
Find the smallest element from
[25, 64]
.The smallest element is
25
(no swap needed).Array remains:
[11, 12, 22, 25, 64]
End of sorting:
- The array is now sorted:
[11, 12, 22, 25, 64]
- The array is now sorted:
1. Pseudocode for Selection Sort:
SelectionSort(arr, n):
For i from 0 to n-1:
minIndex = i
For j from i+1 to n:
If arr[j] < arr[minIndex]:
minIndex = j
If minIndex != i:
Swap arr[i] and arr[minIndex]
2. Algorithm for Selection Sort:
Input: An array
arr[]
of sizen
.Process:
Loop through each element in the array.
In each iteration, find the smallest element from the unsorted portion of the array.
Swap the smallest element found with the first element of the unsorted portion.
Repeat this process for all elements until the array is sorted.
Output: The sorted array.
3. C Code for Selection Sort:
Function to Perform Selection Sort:
#include <stdio.h>
// Function to perform Selection Sort
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
// Traverse through all array elements
for (i = 0; i < n - 1; i++) {
minIndex = i;
// Find the minimum element in the unsorted portion of the array
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
if (minIndex != i) {
temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
4. Explanation of the Code:
selectionSort
function:It loops through each element in the array (
i
from 0 ton-1
).For each iteration, it finds the smallest element in the unsorted portion (
arr[j]
fromi+1
ton
).If a smaller element is found,
minIndex
is updated.After the inner loop, the smallest element (
arr[minIndex]
) is swapped with the element at the current positioni
.