The Selection Sort algorithm is a simple and intuitive sorting algorithm. It works by repeatedly selecting the smallest (or largest, depending on the order) element from the unsorted portion of the array and moving it to the beginning.
Program Structure
#include <stdio.h>
void selectionSort(int arr[], int n) {
int i, j, minIndex, temp;
// Traverse through all array elements
for (i = 0; i < n - 1; i++) {
// Find the minimum element in the unsorted array
minIndex = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// Swap the found minimum element with the first element
temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\\n");
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: \\n");
printArray(arr, n);
selectionSort(arr, n);
printf("Sorted array: \\n");
printArray(arr, n);
return 0;
}
Explanation of the Code
The program consists of the following key components:
- Header Files: The program includes the
stdio.h
library for input and output operations. - Selection Sort Function:
selectionSort(int arr[], int n)
- Parameters:
arr[]
: The array to be sorted.n
: The number of elements in the array.
- Functionality:
- Iterates through the array, finding the minimum element in the unsorted portion.
- Swaps the found minimum element with the first unsorted element.
- Parameters:
- Print Function:
printArray(int arr[], int size)
- Parameters:
arr[]
: The array to print.size
: The number of elements in the array.
- Functionality: Loops through the array and prints each element.
- Parameters:
- Main Function:
int main()
- Initializes an array with sample values.
- Calls the
selectionSort
function to sort the array. - Prints the original and sorted arrays.
How to Compile and Run
To compile and run the program, follow these steps:
-
- Open a terminal (or command prompt).
- Navigate to the directory where you saved the program.
- Compile the program using:
gcc selection_sort.c -o selection_sort
-
- Run the compiled program:
./selection_sort
Conclusion
The Selection Sort algorithm is easy to implement and understand. However, it is not the most efficient for large datasets compared to other algorithms like Quick Sort or Merge Sort. This example provides a foundational understanding of sorting algorithms in C.