Sort numbers using qsort

Submitted by:Tim Kelly

Date added:06 August, 2012

Category:C++

Showing how to sort array of numbers using built-in qsort

Tags: sort numbers , qsort

Code Snippet:

#include <iostream>
#include <stdlib.h>
using namespace std;
int compare(const void *pVal1, const void *pVal2) {
int val1 = *(int*)pVal1;
int val2 = *(int*)pVal2;
return (val1 - val2);
}

int main () {
int i;
// array to sort
int arr[] = {25, -15, 34, 1, 7, -10, 14};
// call qsort
qsort(arr, 7, sizeof(int), compare);
// print sorted values
for (i = 0; i < 7; i++)
cout << arr[i] << " ";
return 0;
}
 
 

Comments