bubble sort in C

Here is an example of a bubble sort algorithm implemented in C:

#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j;
    for (i = 0; i < n-1; i++) {
        for (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;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, n);
    printf("Sorted array: \n");
    for (int i=0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

Explanation of the Bubble Sort Algorithm:

The bubble sort algorithm is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order. The algorithm gets its name from the way smaller elements "bubble" to the top of the list.

The main function calls the bubbleSort function, passing the array arr and the size of the array n.

Inside the bubbleSort function, there are two nested for loops. The outer loop iterates from the first element to the second-to-last element of the array. This is because after each pass through the inner loop, the largest element will be moved to its correct position at the end of the array.

The inner loop iterates from the first element to the (n-i-1)-th element of the array. This is because after each pass through the inner loop, the largest element will be moved to its correct position at the end of the array, so there is no need to compare it again in subsequent iterations.

Inside the inner loop, the algorithm compares adjacent elements arr[j] and arr[j+1]. If arr[j] is greater than arr[j+1], the algorithm swaps these elements using a temporary variable temp. This ensures that the larger element "bubbles up" to its correct position.

After the inner loop completes, the largest element is in its correct position at the end of the array. The outer loop then moves on to the next element. This process continues until the array is fully sorted.

Finally, in the main function, the sorted array is printed using a for loop and the printf function.

This is a basic implementation of the bubble sort algorithm in C. It has a time complexity of O(n^2), making it inefficient for large arrays. However, it is simple to understand and implement.