Open In App

Program to sort an array of strings using Selection Sort

Last Updated : 09 Feb, 2023
Comments
Improve
Suggest changes
38 Likes
Like
Report

Given an array of strings, sort the array using Selection Sort.

Examples: 

Input  : paper true soap floppy flower
Output : floppy, flower, paper, soap, true


Prerequisite : Selection Sort

C++
// C++ program to implement selection sort for
// array of strings.
#include <bits/stdc++.h>
#include <string.h>
using namespace std;
#define MAX_LEN 100

// Sorts an array of strings where length of every
// string should be smaller than MAX_LEN
void selectionSort(char arr[][MAX_LEN], int n)
{
    int i, j, min_idx;

    // One by one move boundary of unsorted subarray
    char minStr[MAX_LEN];
    for (i = 0; i < n-1; i++)
    {
        // Find the minimum element in unsorted array
        int min_idx = i;
        for (j = i + 1; j < n; j++)
        {
            // If min is greater than arr[j]
            if (arr[j]<arr[min_idx])
            {
                // Make arr[j] as minStr and update min_idx
                min_idx = j;
            }
        }

        // Swap the found minimum element with the first element
        if (min_idx != i)
        {
          //swap item[min_idx] and item[i]
            swap(arr[i],arr[min_idx]);
        }
    }
}

// Driver code
int main()
{
    char arr[][MAX_LEN] = {"GeeksforGeeks", "Practice.GeeksforGeeks",
                                                    "GeeksQuiz"};
    int n = sizeof(arr)/sizeof(arr[0]);
    int i;

    cout<<"Given array is\n";
    for (i = 0; i < n; i++)
        cout << i << ": " << arr[i] << endl;

    selectionSort(arr, n);

    cout << "\nSorted array is\n";
    for (i = 0; i < n; i++)
        cout << i << ": " << arr[i] << endl;

    return 0;
}

// This is code is contributed by rathbhupendra
C Java Python3 C# JavaScript

Output
Given array is
0: GeeksforGeeks
1: Practice.GeeksforGeeks
2: GeeksQuiz

Sorted array is
0: GeeksQuiz
1: GeeksforGeeks
2: Practice.GeeksforGeeks

Time Complexity: O(n2), where n represents the size of the character array.
Auxiliary Space: O(100), no extra space is required, so it is a constant.



 


 


Next Article
Article Tags :
Practice Tags :

Similar Reads