Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++

How to use qsort() in C++

Syed Muhammad Ali Mustafa

The qsort() function sorts the given array pointed at by the base pointer. It sorts, in order, through cmp based on on the comparator function.

Library

#include<cstdlib>

Prototype

void qsort(void* base, size_t nelem, size_t size, int (*cmp)(const void*,const void*))

Parameters

1. base

The pointer pointing to the first element of the array.

2. nelem

The total number of elements in the array.

3. size

The size, in bytes, of a single element in the array.

4. cmp

The pointer to a function that compares two elements.

The qsort() function repeatedly calls the function pointed at by cmp to compare elements while sorting. The prototype of the function is as follows:

int cmp(const void* ptr1, const void* ptr2);

The table below illustrates the action associated with each different value returned by cmp():

Return Value Action
< 0 The element pointed by ptr1 is placed before the element pointed by ptr2.
== 0 The element pointed by ptr1 is equivalent to the element pointed by ptr2.
> 0 The element pointed by ptr1 is placed after the element pointed by ptr2.

Return type

The return type of the function is void. It does not return value.

Code

#include <iostream>
#include <cstdlib>

int ascending(const void * x, const void * y) {
   return (*(int*)x - *(int*)y);
}

int descending(const void * x, const void * y) {
   return (*(int*)y - *(int*)x);
}

int main () {
  const int n = 5;
  int values[n] = {73, 58, 95, 7, 19};

  std::cout << "Before sorting the array: ";
  for(int i = 0 ; i < n; ++i) {
    std::cout << values[i] << " ";
  }

  qsort(values, n, sizeof(int), ascending);
  std::cout << "\nAfter sorting the array in ascending order: ";
  for(int i = 0 ; i < n; ++i) {   
    std::cout << values[i] << " ";
  }

  qsort(values, n, sizeof(int), descending);
  std::cout << "\nAfter sorting the array in descending order: ";
  for(int i = 0 ; i < n; ++i) {   
    std::cout << values[i] << " ";
  }

  return 0;
}

RELATED TAGS

c++

CONTRIBUTOR

Syed Muhammad Ali Mustafa
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring