c語言如何把輸入的數(shù)字倒序排序

小億
295
2024-02-18 11:28:18
欄目: 編程語言

可以使用冒泡排序算法來實(shí)現(xiàn)將輸入的數(shù)字按照倒序排序的功能。具體代碼如下所示:

#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;
            }
        }
    }
}

int main() {
    int n;
    printf("Enter the number of elements: ");
    scanf("%d", &n);

    int arr[n];
    printf("Enter the elements: ");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    bubbleSort(arr, n);

    printf("Sorted array in descending order: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

在上述代碼中,我們先輸入數(shù)字的個(gè)數(shù)n,然后輸入n個(gè)數(shù)字存儲(chǔ)在數(shù)組arr中。接著調(diào)用bubbleSort函數(shù)對(duì)數(shù)組進(jìn)行倒序排序,最后輸出排序后的數(shù)組。

0