Need help with a C++ assignment? Get affordable C++ homework help.

Sort numbers using qsort code snippet

Summary

Source code of C++ program, showing how to sort array of numbers using built-in qsort.

Source code

C++: qsort.cpp

#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;

}

 

Sample run

C/C++

-15 -10 1 7 14 25 34