qsort() sample program in C++

By: Norman Chap Emailed: 1644 times Printed: 2112 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

At times you may want to sort a table or an array; qsort() provides a quick and easy way to do so. The hard part of using qsort() is setting up the structures to pass in.

qsort() takes four arguments. The first is a pointer to the start of the table to be sorted (an array name works just fine), the second is the number of elements in the table, the third is the size of each element, and the fourth is a pointer to a comparison function.

The comparison function must return an int, and must take as its parameters two constant void pointers. void pointers aren't used very often in C++, as they diminish the type checking, but they have the advantage that they can be used to point to items of any type. If you were writing your own qsort() function, you might consider using templates instead. Listing below illustrates how to use the standard qsort() function.

Using qsort().

1:     /* qsort example */
2:
3:     #include <iostream.h>
4:     #include <stdlib.h>
5:
6:     // form of sort_function required by qsort
7:     int sortFunction( const void *intOne, const void *intTwo);
8:
9:     const int TableSize = 10;  // array size
10:
11:    int main(void)
12:    {
13:       int i,table[TableSize];
14:
15:       // fill the table with values
16:       for (i = 0; i<TableSize; i++)
17:       {
18:          cout << "Enter a number: ";
19:          cin >> table[i];
20:       }
21:       cout << "\n";
22:
23:       // sort the values
24:       qsort((void *)table, TableSize, sizeof(table[0]), sortFunction);
25:
26:       // print the results
27:       for (i = 0; i < TableSize; i++)
28:          cout << "Table [" << i << "]: " << table[i] << endl;
29:
30:       cout << "Done." << endl;
31:     return 0;
32:    }
33:
34:    int sortFunction( const void *a, const void *b)
35:    {
36:       int intOne = *((int*)a);
37:       int intTwo = *((int*)b);
38:       if (intOne < intTwo)
39:          return -1;
40:       if (intOne == intTwo)
41:          return 0;
42:       return 1;
43: }
Output: Enter a number: 2
Enter a number: 9
Enter a number: 12
Enter a number: 873
Enter a number: 0
Enter a number: 45
Enter a number: 93
Enter a number: 2
Enter a number: 66
Enter a number: 1

Table[0]: 0
Table[1]: 1
Table[2]: 2
Table[3]: 2
Table[4]: 9
Table[5]: 12
Table[6]: 45
Table[7]: 66
Table[8]: 93
Table[9]: 873
Done.

Analysis: On line 4, the standard library header is included, which is required by the qsort() function. On line 7, the function sortFunction() is declared, which takes the required four parameters.

An array is declared on line 13 and filled by user input on lines 16-20. qsort() is called on line 24, casting the address of the array name table to be a void*.

Note that the parameters for sortFunction are not passed to the call to qsort(). The name of the sortFunction, which is itself a pointer to that function, is the parameter to qsort().

Once qsort() is running, it will fill the constant void pointers a and b with each value of the array. If the first value is smaller than the second, the comparison function must return -1. If it is equal, the comparison function must return 0. Finally, if the first value is greater than the second value, the comparison function must return 1. This is reflected in the sortFunction(), as shown on lines 34 to 43.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(6)


1. View Comment

DO NOT USE QSORT IN A C++ CODE.

If this is a tutorial on C++, then try std::sort in the <algorithm> library:

http://www.cplusplus.com/reference/algorithm/sort.html

And include &lt;iostream&gt; instead of the obsolete &lt;iostream.h&gt;.


View Tutorial          By: paercebal at 2008-08-13 05:06:45
2. View Comment

How do use qsort to sort lines in text file?

View Tutorial          By: kenny at 2008-11-18 08:59:55
3. View Comment

but include<iostream> is main function.

View Tutorial          By: glen at 2009-02-03 22:19:22
4. View Comment

good!

View Tutorial          By: rey.ryan at 2009-03-14 05:49:28
5. View Comment

thanks
for your clear and precise explanation :)


View Tutorial          By: Tausiq at 2009-09-05 07:27:49
6. View Comment

Thanks

View Tutorial          By: Bad Programmer at 2011-11-23 10:43:49

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Norman Chap
The break Statement example in Java
Stored Procedures example in SQL
JDBC and Tomcat context settings
File read and write - sample program in C
Pointers and Function Arguments in C
Writing the first Struts application
goto and labels in C
External Variables and Scope in C
Multiple inheritance example in C++
qsort() sample program in C++
Image and ImageItem sample program in J2ME
SimpleDateFormat sample program in Java
Observable class and the sample program in Java

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Stray or Dangling Pointers in C++
Sorting an array of Strings in C++
A Brief History of C++
C++ and Object-Oriented Programming
Getting Started with C++
Classes with Other Classes as Member Data in C++
The indirection operator (*) - dereference operator.
Dot (.) vs Arrow (->) to access data members in C++
What Is a Reference in C++?
atoi(), itoa() in C++
qsort() sample program in C++
Opening files for read and write in C++
Sum of 1 to N in C++
Programming errors a compiler will detect in C++
Calculating total based on the given quantity and price in C++
Most Emailed Articles (in C++)
Returning values from a function in C++
while (1) Loops in C++
Using Comments in a C++ Program
Specifying default values to function parameters in C++
continue and break statements in C++
The indirection operator (*) - dereference operator.
Difference between Procedural, Structured, and Object-Oriented Programming
C++ and Object-Oriented Programming
How to use Enumerated constants in C++
Advanced if Statements in C++
while Loops in C++
Converting Pointer Parameters in C++ to Java
assert() Versus Exceptions in C++
Compute the square root of the sum of the squares of an array in C++
A Brief History of C++