C Program to Sort an array of names or strings

CServer Side ProgrammingProgramming

In this problem, we are given an array of string. Our task is to create a c program to sort an array of name or string. This program will sort all the names we have given in the input in ascending alphabetical order.

Let’s take an example to understand the problem,

Input

namesArray = ["Rishabh", "Jyoti", "Palak", "Akash"]

Output

["Akash", "jyoti", "palak", "Rishabh"]

To solve this we will use the qsort() function of the standard template library as we know sorting of integer values the thing that changes here is we are considering string for comparison instead of integer values.

So, the comparator that is used in the qsort() will be changed, and strcmp() will be used to compare the strings in the comparator. Using this we can sort the array of names or strings.

C Program to Sort an array of names or strings

Example

 Live Demo

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int comparator(const void* str1, const void* str2) {
   if(strcmp(*(const char**)str1, *(const char**)str2) >= 0)
      return 1;
   else return 0;
}
int main() {
   const char* arr[] = {"Rishabh", "Jyoti", "Palak", "Akash"};
   int n = sizeof(arr) / sizeof(arr[0]);
   printf("\nGiven array of names: \t");
   for (int i = 0; i < n; i++) printf("%s \t", arr[i]);
      qsort(arr, n, sizeof(const char*), comparator);
   printf("\nSorted array of names: \t");
   for (int i = 0; i < n; i++)
      printf("%s \t", arr[i]);
   return 0;
}

Output

Given array of names:  Rishabh Jyoti Palak Akash
Sorted array of names: Akash   Jyoti Palak Rishabh
raja
Published on 18-Jul-2020 06:17:53
Advertisements