Sort an array of strings


StringViews 1425

Given an array of strings, write a function to sort them alphabetically

Example

INPUT :
arr[] = {“bekz”,”bcdk”,”akleedf” }

OUTPUT :
“akleedf” , “bcdk”, “bekz”

Here, in above example we can see first string will be “akleedf” as ‘a’ comes first in order. For the next two strings ‘b’ is common so check next character, ‘c’ comes before ‘e’ so next string will be “bcdk”.

Algorithm

1. Sort the given array using standard library function in c++, ie sort(arr, arr+n) where n is the size of the array

2. Print the sorted array

C++ Program

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string arr[] = {"bekz","bcdk","akleedf" };
    //finding the size of the array
    int n = sizeof(arr)/sizeof(arr[0]);

    //Standard Library Function to sort the array 
    sort(arr,arr+n);
    //printing the sorted array
    for (int i = 0; i < n; ++i)
    {
        cout<<arr[i]<<endl;
    }
}

Try It

 

Translate ยป