HIDE NAV

Sorting Arrays with qsort in C

This source shows how to use the stdlib.h function qsort to order values in an array from least to greatest.

qsortDemo.c


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

int comparisonFn(const void *p1, const void *p2);

int main(void) {

	int ourArray[] = {23,0,-1,3,3288,-27};
	printf("original array:\n");
	for (int i = 0; i < 6; i++){
		printf("[%d]:   %d\n", i, ourArray[i]);
	}

	printf("sorted array:\n");
	qsort(ourArray, 6, sizeof(int), comparisonFn);
	for (int i = 0; i < 6; i++){
		printf("[%d]:   %d\n", i, ourArray[i]);
	}

	return 0;
}

int comparisonFn(const void *p1, const void *p2){
	int value1 = *(int*)p1;
	int value2 = *(int*)p2;
	return value1 - value2;
}