How to write code in C for sorting from smallest to largest?

Here is an example of C code using the bubble sort algorithm to sort an array of integers in ascending order.

#include <stdio.h>

void bubbleSort(int arr[], int n) {

    int i, j, temp;

    

    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]

                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]);

    int i;

    

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

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

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

    }

    

    bubbleSort(arr, n);

    

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

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

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

    }

    

    return 0;

}

The `bubbleSort` function in the above code uses the bubble sort algorithm to sort the incoming array. In the `main` function, an integer array is created and the `bubbleSort` function is called for sorting. Finally, the array before and after sorting is displayed. Running this program will display the following result:

排序前的数组:

64 34 25 12 22 11 90 

排序后的数组:

11 12 22 25 34 64 90

This is a basic sorting algorithm, you can also try other more efficient sorting algorithms for sorting in ascending order, such as Quick Sort, Merge Sort, etc.

广告
Closing in 10 seconds
bannerAds