Qsort In C

Example

#include<stdlib.h>

Syntax of the function:

Example

qsort(array, number, size, function)

array : The array to be sorted.

number : The count of elements in the array that we intend to arrange in order

size : Size of an individual element of the array

function: A custom comparator function that must be implemented in a specific format:

Specified format of the function:

Example

int compare( const void* a, const void* b) 

{                                                       
}
  • qsort calls the compare function for every two elements in the array.
  • Arguments a and b are two void pointers to point to the two elements to be compared.
  • we must write the body of compare in the way that it should return: 0 if two elements are equal -1 or any other negative integer if the first element is less than the second element 1 or any other positive number if the first element is greater than the second.
  • The name of the comparing function can be anything, but the name must be exactly given as an argument to the qsort function.
  • const void* a means a is a void pointer whose value is fixed. Before using, we need to typecast a void pointer to some data type.
  • 0 if two elements are equal
  • -1 or any other negative integer if the first element is less than the second element
  • 1 or any other positive number if the first element is greater than the second.
  • Now, we will explore the functions for sorting arrays of different data types.

    1. Sorting Integers:

    Example
    
    #include<stdio.h>
    #include<stdlib.h>
    int compare(const void* num1, const void* num2) // comparing function
    {
    	int a = *(int*) num1;
    	int b = *(int*) num2;
    	if(a > b)
    	{
    		return 1;
    	}
    	else if(a < b)
    	{
    		return -1;
    	}
    	return 0;
    }
    int main()
    {
    	int arr[50], n, i;
    	printf("Enter the size of the array to be sorted: ");
    	scanf("%d", &n);
    	printf("\nEnter elements into the array: ");
    	for(i = 0; i < n; i++)
    	{
    		scanf("%d", &arr[i]);
    	}
    	qsort(arr, n, sizeof(int), compare);
    	printf("\nThe sorted array: ");
    	printf("\n[");
    	for(i = 0; i < n; i++)
    	{
    		if(i == n-1) // To prevent a comma(,) after the last element
    		{
    			printf("%d", arr[i]);
    			break;
    		}
    		printf("%d, ", arr[i]);
    	}
    	printf("]");
    }
    

Output:

Output

Enter the size of the array to be sorted: 5
Enter elements into the array: 98 34 89 0 2
The sorted array:
[0, 2, 34, 89, 98]

Understanding:

In these two lines:

int a = (int) num1;

int b = (int) num2;

The array being processed is categorized as type <int>. As a result, it is essential to convert the generic pointers to integer pointers prior to any memory allocation activities. The values pointed to by the two pointers were saved in separate integer variables, namely a and b. Subsequently, we conducted a comparison between these two values utilizing the appropriate operators.

Instead of utilizing two additional temporary variables, we can condense the code into a single line:

Example

int compare(const void* num1, const void* num2)
{
	return *(int*)a - *(int*)b;
}
  • When a is equal to b, the function returns 0. In cases where a is greater than b, a positive integer is the output; while if a is less than b, a negative integer is returned.
  • 2. Sorting strings

    Example
    
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    int compare(const void* num1, const void* num2)
    {
    	//char **a = (char**)num1;
    	//char **b = (char**)num2;
    	//return strcmp(*a, *b);
    	return strcmp(*(char**)num1, *(char**)num2);
    	
    }
    int main()
    {
    	int n, i;
    	char* arr[50];
    	printf("Enter the size of the array to be sorted: ");
    	scanf("%d", &n);
    	printf("\nEnter elements into the array: ");
    	for(i = 0; i < n; i++)
    	{
    		arr[i] = malloc(100* sizeof(char));
    		scanf("%s", arr[i]);
    	}
    	qsort(arr, n, sizeof(char*), compare);
    	printf("\nThe sorted array: ");
    	printf("\n[");
    	for(i = 0; i < n; i++)
    	{
    		if(i == n-1)
    		{
    			printf("%s", arr[i]);
    			break;
    		}
    		printf("%s, ", arr[i]);
    	}
    	printf("]");
    }
    

Output:

Output

Enter the size of the array to be sorted: 5
Enter elements into the array: hi hello how are you
The sorted array:
[are, hello, hi, how, you]

Understanding:

  • We have an array of strings. The difference between an integer array and a string array is that: An integer array is a collection of integers A string array is a collection of character arrays/character pointers.
  • Hence, in the compare function, we need to typecast the void pointers to (char*)a and not (char)a. [[string 1], [string 2]?] When we use char*, iLogic Practices to the array, and then, to point to a string in the array, we need a double pointer.
  • We used the strcmp function here. The function is defined in the string.h header file. We need to include it first.
  • The function returns : 0 if both strings are the same 1 if the ASCII value of a character in the string is greater than the corresponding character in the second string -1 if the ASCII value of a character in the string is less than the corresponding character in the second string.
  • An integer array is a collection of integers
  • A string array is a collection of character arrays/character pointers.
  • 0 if both strings are the same
  • 1 if the ASCII value of a character in the string is greater than the corresponding character in the second string
  • -1 if the ASCII value of a character in the string is less than the corresponding character in the second string.
  • 3. Sorting an Array of Structure

    Example
    
    #include<stdio.h>
    #include<stdlib.h>
    struct Structure
    {
    	int num1;
    	int num2;
    }s;
    typedef struct Structure data;
    int compare(const void* p, const void* q)
    {
    	data *a = (data *)p;
    	data *b = (data *)q;
    	int first = (a -> num1)- (b -> num1);
    	int second = (a -> num2)- (b -> num2);
    	if(first == 0)
    	{
    		return second;
    	}
    	return first;
    }
    int main()
    {
    	data array[5];
    	int i = 0;
    	printf("Original array: \n");
    	printf("[[");
    	for(i = 0; i < 5; i++)
    	{
    		array[i].num1 = rand()%10;
    		array[i].num2 = rand()%10;
    		if(i == 4)
    		{
    			printf("%d, %d]]", array[i].num1, array[i].num2);
    			break;
    		}
    		printf("%d, %d], [", array[i].num1, array[i].num2);
    	}
    	qsort(array, 5, sizeof(s), compare);
    	printf("\nSorted array: \n");
    	printf("[[");
    	for(i = 0; i < 5; i++)
    	{
    		if(i == 4)
    		{
    			printf("%d, %d]]", array[i].num1, array[i].num2);
    			break;
    		}
    		printf("%d, %d], [", array[i].num1, array[i].num2);
    	}
    }
    

Output:

Output

Original array:
[[1, 7], [4, 0], [9, 4], [8, 8], [2, 4]]
Sorted array:
[[1, 7], [2, 4], [4, 0], [8, 8], [9, 4]]

Understanding:

We have defined an array consisting of elements of type Structure, indicating that each element within the array is itself an array of structure elements. Within this program, the structure comprises a pair of integer elements. Our objective is to arrange the array in ascending order based on the value of the first element of the Structure. In cases where two first elements are equivalent, the sorting should be performed using the second element.

Example:

[[1, 2], [3, 4], [1, 4]]

Sorted array: [[1, 2], [1, 4], [3, 4]]

We employed the rand function to produce random elements within the array. Within the compare function, it is necessary to cast the two pointers to the structure type.

The unique feature of utilizing the qsort function lies in the ability to create a custom comparison function tailored to specific requirements. This allows for sorting selected elements within an array while leaving others in their original order.

Input Required

This code uses input(). Please provide values below: