How to implement bubble sort in C language for ascending order?

In C language, the bubble sort algorithm can be used to sort an array in ascending order. The basic idea of bubble sort is to repeatedly swap adjacent elements, gradually moving the larger elements towards the end of the array.

Here is an example code implementing ascending order sorting using the bubble sort algorithm.

#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[] = {5, 2, 8, 12, 3};

    int n = sizeof(arr) / sizeof(arr[0]);

    printf("原始数组: ");

    for (int i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

    bubbleSort(arr, n);

    printf("\n排序后的数组: ");

    for (int i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

    return 0;

}

Output results:

原始数组: 5 2 8 12 3

排序后的数组: 2 3 5 8 12

In the example code above, the `bubbleSort()` function takes an integer array and the size of the array as parameters. It uses two nested loops to iterate through the array and move the larger elements to the right. Finally, the `main()` function sorts the array by calling the `bubbleSort()` function and outputs the sorted result.

Please note that in practical applications, the bubble sort algorithm may not be the best choice because its time complexity is O(n^2), making it less efficient for handling large datasets. More efficient sorting algorithms such as quicksort or mergesort can be used as alternatives to bubble sort.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds