How to Sort Function in C

Jinku Hu Feb 02, 2024
  1. Use the qsort Function to Sort an Array of Integers in C
  2. Use the qsort Function to Sort an Array of Strings in C
How to Sort Function in C

This article will explain several methods of how to use the standard library sort function in C.

Use the qsort Function to Sort an Array of Integers in C

The qsort function implements a somewhat generic sorting operation for different data element arrays. Namely, qsort takes the pointer to function as the fourth argument to pass the comparison function for a given array of elements. In this case, we implemented the intCompare function to compare integer array using qsort.

Note that intCompare should have the type - int (*compar)(const void *, const void *) as specified by the qsort prototype. Consequently, we are casting the p1/p2 arguments to int pointers first and then dereferencing them to access the values themselves.

The return value of the comparison function must be the integer less than 0 if the first parameter is less than the other, greater than 0 if the first parameter is larger than the second, and zero if two parameters are equal.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int intCompare(const void *p1, const void *p2) {
  int int_a = *((int *)p1);
  int int_b = *((int *)p2);

  if (int_a == int_b)
    return 0;
  else if (int_a < int_b)
    return -1;
  else
    return 1;
}

void printIntegers(int arr[], size_t size) {
  for (size_t i = 0; i < size; i++) printf("%4d | ", arr[i]);
  printf("\n");
}

int main(int argc, char *argv[]) {
  int arr2[] = {53, 32, 12, 52, 87, 43, 93, 23};

  printIntegers(arr2, 8);
  qsort(arr2, 8, sizeof(int), intCompare);
  printIntegers(arr2, 8);

  exit(EXIT_SUCCESS);
}

Output:

53 |   32 |   12 |   52 |   87 |   43 |   93 |   23 |
12 |   23 |   32 |   43 |   52 |   53 |   87 |   93 |

Use the qsort Function to Sort an Array of Strings in C

qsort can sort the string array in ascending order with strcmp acting as the comparison function. In this case, we declared and initialized the array of char pointers, elements of which are sorted with a single call to the qsort function.

Notice that the casting and dereferencing is the necessary part of the comparison function as it takes both parameters as void pointer types.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int stringCompare(const void *p1, const void *p2) {
  return strcmp(*(char *const *)p1, *(char *const *)p2);
}

void printStrings(char *arr[], size_t size) {
  for (size_t i = 0; i < size; i++) printf("%10s | ", arr[i]);
  printf("\n");
}

int main(int argc, char *argv[]) {
  char *arr[] = {"jello", "hello", "mello", "zello", "aello"};

  printStrings(arr, 5);
  qsort(arr, 5, sizeof(char *), stringCompare);
  printStrings(arr, 5);

  exit(EXIT_SUCCESS);
}

Output:

jello |      hello |      mello |      zello |      aello |
aello |      hello |      jello |      mello |      zello |

Alternatively, one can reimplement the previous example code so that the user provides the string array with program arguments and the sorted array is printed as an output. This time, it’s essential to check if there are enough arguments passed to sort before proceeding to call qsort.

Notice that, stringCompare function directly returns the value of the strcmp call as the latter has the same specification of return values as the comparison function for the qsort.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static int stringCompare(const void *p1, const void *p2) {
  return strcmp(*(char *const *)p1, *(char *const *)p2);
}

void printStrings(char *arr[], size_t size) {
  for (size_t i = 0; i < size; i++) printf("%10s | ", arr[i]);
  printf("\n");
}

int main(int argc, char *argv[]) {
  if (argc < 3) {
    printf("Usage: ./program string_0 string_1 string_2...\n");
    exit(EXIT_FAILURE);
  }

  printStrings(argv + 1, argc - 1);
  qsort(argv + 1, argc - 1, sizeof(char *), stringCompare);
  printStrings(argv + 1, argc - 1);

  exit(EXIT_SUCCESS);
}
Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook