Home C-tutorials C array sort example
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

C array sort example

Advertisement
For sorting an array, we have used the qsort function. This function provides the implementation of quicksort algorithm to sort the elements of an array.

C array sort example

     

In this section, you will learn how to sort an array in C.

For sorting an array, we have used the qsort function. This function provides the implementation of quicksort algorithm to sort the elements of an array.


Syntax of the function:
qsort(array, sizeof(array), sizeof(type), comparison_fn).

In the example, we have created a comparison function sort to compare two elements. For this we have passed two parameters (x and y ) which are pointers to elements and will return an int value by comparing them. This method compares each pair of elements. This function can be declared as:
int sort (const void * x, const void * y );

 (*(int*)x - *(int*)y)- The parameters x and y  checks for each pair of elements considering the elements as x and y. If x is found greater than y, then x goes before y otherwise, x goes after y. In case if x = y, then it remains on the same position.

<stdlib.h> - This header file stands for standard library which includes functions involving String, Memory, Environment, Sorting and Searching, Math and Multibyte

Here is the code:

ARRAYSOR.C

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
int array[] 903332880498303625 };
int sort(const void *x, const void *y) {
  return (*(int*)x - *(int*)y);
}
void main() {
  clrscr();
  int i;
  qsort(array, 10, sizeof(int), sort);
  for (i=0; i<10; i++) {
  printf("%d ", array[i]);
  }
  getch();
}

Output will be displayed as:

ARRAYSOR.EXE

Download Source Code:

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 5, 2009

Related Tutorials

Ask Questions?    Discuss: C array sort example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
James
June 15, 2011
x

this is not C, this is C++..
PRATEEK GERA
September 19, 2011
C

NICE AND HELPFUL SITE
bhavesh patel
December 11, 2011
fundamentals of programming

its awesome ....
Ares Remo
December 17, 2011
weak!

Just be better next time...
Harmeet Singh
February 16, 2012
Sorting of array

how sort the array with with out use in build funtion
pranav.sivan
March 28, 2012
array sorting

how to sort elements in an array in ascending and descending order ,using bubble sort, selection sort
ben sarfo
May 7, 2012
programming

a beginner.
Gaylord Simpsan
November 28, 2012
Programming and Software Engeneering

I doesn't work, bro..
Hong VA
August 5, 2013
C programming

it not c
DMCA.com