Mastering Sorting Algorithms in C

C Programming @ Freshers.in

Sorting is a fundamental operation in computer science, and understanding sorting algorithms is crucial for every programmer. In this comprehensive guide, we will explore various sorting algorithms in the C programming language, providing detailed explanations, practical examples, and real data to help you master these essential techniques.

Bubble Sort in C

Bubble Sort is one of the simplest sorting algorithms. It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.

Example: Implementing Bubble Sort in C

#include <stdio.h>
void bubbleSort(int arr[], int n) {
    int temp;
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > 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]);
    printf("Unsorted Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    bubbleSort(arr, n);
    printf("\nSorted Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:

Unsorted Array: 64 34 25 12 22 11 90 
Sorted Array: 11 12 22 25 34 64 90 

In this example, we implement the Bubble Sort algorithm to sort an array of integers.

Selection Sort in C

Selection Sort is another simple sorting algorithm that sorts an array by repeatedly finding the minimum element from the unsorted part and putting it at the beginning.

Example: Implementing Selection Sort in C

#include <stdio.h>
void selectionSort(int arr[], int n) {
    int minIdx, temp;
    for (int i = 0; i < n - 1; i++) {
        minIdx = i;
        for (int j = i + 1; j < n; j++) {
            if (arr[j] < arr[minIdx]) {
                minIdx = j;
            }
        }
        temp = arr[i];
        arr[i] = arr[minIdx];
        arr[minIdx] = temp;
    }
}
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]);
    }
    selectionSort(arr, n);
    printf("\nSorted Array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    return 0;
}

Output:

Unsorted Array: 64 34 25 12 22 11 90 
Sorted Array: 11 12 22 25 34 64 90 

In this example, we implement the Selection Sort algorithm to sort an array of integers.

Author: user