Sort an Array in Descending Order

Code

#include <stdio.h>
#include <stdint.h>

void bubble_sort_desc(uint8_t *arr, uint8_t n) {
uint8_t t=0;
int swapped;
int limit=n-1;

do{
    swapped=0;
    for(int i = 0; i<limit; i++){
        if(arr[i]<arr[i+1]){
            t=arr[i];
            arr[i]=arr[i+1];
            arr[i+1]=t;
        
            swapped = 1;
        }
    }
    limit--;
} while (swapped);
}

int main() {
    uint8_t n;
    scanf("%hhu", &n);
    uint8_t arr[100];

    for (uint8_t i = 0; i < n; i++) {
        scanf("%hhu", &arr[i]);
    }

    bubble_sort_desc(arr, n);

    for (uint8_t i = 0; i < n; i++) {
        printf("%hhu", arr[i]);
        if(i < n-1){
            printf(" ");
        }
    }

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 10 3 5 2 7

Expected Output

10 7 5 3 2