

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
C Program to Sort an array of names or strings
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("\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
- Related Questions & Answers
- Sort an array of strings according to string lengths in C++
- C program to sort names in alphabetical order
- C program to sort an array by using merge sort
- C++ Program to Sort an Array of 10 Elements Using Heap Sort Algorithm
- C Program to Reverse Array of Strings
- C program to sort an array in an ascending order
- C# program to sort an array in descending order
- C program to sort an array in descending order
- C program to sort an array of ten elements in an ascending order
- C program to sort names in alphabetical order using structures
- C# Program to search for a string in an array of strings
- Making a Palindrome pair in an array of words (or strings) in C++
- Sort an Array of string using Selection sort in C++
- Sort an Array in C++
- How to sort an array of dates in C/C++?
Advertisements