Sorting Algorithms

Sorting algorithms are used to arrange the elements of a list or array in a particular order, such as ascending or descending.

Common Sorting Algorithms

Bubble Sort

Bubble Sort is a simple comparison-based sorting algorithm where each element in the array is compared with the next one. If an element is larger than the next one, the two elements are swapped. This process is repeated until the entire array is sorted.

Bubble Sort

#include <stdio.h>
void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, n);
    printf("Sorted array: ");
    printArray(arr, n);
    return 0;
}

Output

Sorted array: 11 12 22 25 34 64 90