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 245 views
1 answer 174 views
1 answer 260 views
...