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,907 questions

51,839 answers

573 users

How to use qsort function to sort int array elemets in ascending 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*)a - *(int*)b );
}

void print_array(int arr[], int len)
{
    int i;
     
    for (i = 0; i < len; i++) printf("%4d", arr[i]);
}
 

/* 
run:

   5   6  10  10   8  10   3   2   6   7
   2   3   5   6   6   7   8  10  10  10

*/




answered Sep 27, 2014 by avibootz
edited Sep 27, 2014 by avibootz

Related questions

2 answers 261 views
1 answer 193 views
1 answer 279 views
...