Sorting is a fundamental algorithmic operation and is widely used in various applications, such as searching, data analysis, and optimisation. There are several sorting algorithms available in C programming, each with its own strengths and weaknesses. The choice of sorting algorithm depends on the size of the data, the distribution of the data, and the specific requirements of the application.
Let's discuss the commonly used Selection Sort algorithm in C programming:
- Selection Sort:
Selection Sort is another simple sorting algorithm that repeatedly finds the minimum element from the unsorted part of the list and places it at the beginning. The subarray to the left is sorted, and the process continues until the whole array is sorted.
Example implementation of Selection Sort in C:
c#include <stdio.h>
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
void selectionSort(int arr[], int n) {
int i, j, min_idx;
for (i = 0; i < n - 1; i++) {
min_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}
swap(&arr[i], &arr[min_idx]);
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Original array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
selectionSort(arr, n);
printf("\nSorted array: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
return 0;
}