How to Implement Sorting Algorithms in C Programming
Bubble Sort
Bubble Sort is a simple algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.
Code Example:
#include <stdio.h>
void bubble sort(int arr[], int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubble sort(arr, n);
print("Sorted array: \n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}
Selection Sort
Selection Sort works by dividing the list into two parts: a sorted part and an unsorted part. It repeatedly selects the smallest (or largest) element from the unsorted part and moves it to the end of the sorted part.
Code Example:
#include <stdio.h>
void selection sort(int arr[], int n) {
int i, j, min_idx, temp;
for (i = 0; i < n-1; i++) {
// Find the minimum element in the unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selection sort(arr, n);
printf("Sorted array: \n");
for (int i=0; i < n; i++)
print("%d ", arr[i]);
return 0;
}
Insertion Sort
Insertion Sort builds the sorted array one item at a time. It takes each element from the list and inserts it into its correct position in the sorted part of the array.
Code Example:
#include <stdio.h>
void insertion sort(int arr[], int n) {
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
// Move elements of arr[0..i-1] that are greater than key to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr)/sizeof(arr[0]);
insertion sort(arr, n);
printf("Sorted array: \n");
for (int i = 0; i < n; i++)
print("%d ", arr[i]);
return 0;
}
Conclusion
Sorting algorithms are essential for organizing data efficiently. In C programming, Bubble Sort is best for small datasets due to its simplicity; Selection Sort is useful when the memory writes are costly, and Insertion Sort is efficient for datasets that are already partially sorted. Understanding these basic sorting algorithms will give you a strong foundation for data manipulation and algorithm design.