How to implement bubble sort in the C programming language?

Bubble sort is a fundamental sorting algorithm, and below is the implementation of bubble sort algorithm in C language.

#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]) {
                // 交换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("排序后的数组:\n");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    
    return 0;
}

The bubbleSort function in the above code implements the bubble sort algorithm. It uses two nested loops to iterate through the array and compares adjacent elements. If the element in the front is greater than the element behind it, they are swapped. This way, after each iteration, the largest element “bubbles” to the end of the array. This process is repeated until the entire array is sorted.

In the main function, we create a test array and pass it to the bubbleSort function for sorting. Finally, we print the sorted array.

bannerAds