
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort an Array of Names or Strings in C
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
#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("
Given array of names: \t"); for (int i = 0; i < n; i++) printf("%s \t", arr[i]); qsort(arr, n, sizeof(const char*), comparator); printf("
Sorted 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
Advertisements