Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,939 questions

51,876 answers

573 users

How to use qsort function to sort int array elemets in descending order in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
  
#define N 10
 
void print_array(int arr[], int len);
int compare(const void *a, const void *b);
  
int main(void)
{
    int i, arr[N] = { 0 };   
         
    srand(time(NULL));
    for (i = 0; i < N; i++)
         arr[i] = rand() % 10 + 1;
             
    print_array(arr, N);
    printf("\n");
     
    qsort(arr, N, sizeof(int), compare);
    print_array(arr, N);
    printf("\n");
      
    return 0;
}
  
int compare(const void *a, const void *b)
{
   return ( *(int*)b - *(int*)a );
}
 
void print_array(int arr[], int len)
{
    int i;
      
    for (i = 0; i < len; i++) printf("%4d", arr[i]);
}
  
 
/*
run:
 
   8  10   8  10   5   8   8   7  10   8
  10  10  10   8   8   8   8   8   7   5

*/


answered Sep 27, 2014 by avibootz
...