Program to sort an array of strings using Selection Sort

08 Jun, 2022
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
Java
Python3
C#
Javascript
// 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_LENvoid 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;        strcpy(minStr, arr[i]);        for (j = i + 1; j < n; j++)        {            // If min is greater than arr[j]            if (strcmp(minStr, arr[j]) > 0)            {                // Make arr[j] as minStr and update min_idx                strcpy(minStr, arr[j]);                min_idx = j;            }        }         // Swap the found minimum element with the first element        if (min_idx != i)        {            char temp[MAX_LEN];            strcpy(temp, arr[i]); //swap item[pos] and item[i]            strcpy(arr[i], arr[min_idx]);            strcpy(arr[min_idx], temp);        }    }} // Driver codeint 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 program to implement selection sort for// array of strings.#include <stdio.h>#include <string.h>#define MAX_LEN 100  // Sorts an array of strings where length of every// string should be smaller than MAX_LENvoid 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;        strcpy(minStr, arr[i]);        for (j = i+1; j < n; j++)        {            // If min is greater than arr[j]            if (strcmp(minStr, arr[j]) > 0)            {                // Make arr[j] as minStr and update min_idx                strcpy(minStr, arr[j]);                min_idx = j;            }        }          // Swap the found minimum element with the first element        if (min_idx != i)        {            char temp[MAX_LEN];            strcpy(temp, arr[i]); //swap item[pos] and item[i]            strcpy(arr[i], arr[min_idx]);            strcpy(arr[min_idx], temp);        }    }}  // Driver codeint main(){    char arr[][MAX_LEN] = {"GeeksforGeeks", "Practice.GeeksforGeeks",                                                    "GeeksQuiz"};    int n = sizeof(arr)/sizeof(arr[0]);    int i;      printf("Given array is\n");    for (i = 0; i < n; i++)        printf("%d: %s \n", i, arr[i]);      selectionSort(arr, n);      printf("\nSorted array is\n");    for (i = 0; i < n; i++)        printf("%d: %s \n", i, arr[i]);      return 0;}
// Java program to implement selection sort// on array of stringsimport java.util.*;import java.io.*; class Main{     // Sorts an array of stringsstatic void selectionSort(String arr[],int n){    // One by one move boundary of unsorted subarray    for(int i = 0; i < n - 1; i++)    {             // Find the minimum element in unsorted array        int min_index = i;        String minStr = arr[i];        for(int j = i + 1; j < n; j++)        {                         /*compareTo() will return a -ve value,            if string1 (arr[j]) is smaller than string2 (minStr)*/            // If arr[j] is smaller than minStr                     if(arr[j].compareTo(minStr) < 0)            {                // Make arr[j] as minStr and update min_idx                minStr = arr[j];                min_index = j;            }        }     // Swapping the minimum element    // found with the first element.    if(min_index != i)    {        String temp = arr[min_index];        arr[min_index] = arr[i];        arr[i] = temp;    }    }} // Driver codepublic static void main(String args[]){    String arr[] = {"GeeksforGeeks",                    "Practice.GeeksforGeeks",                    "GeeksQuiz"};    int n = arr.length;        System.out.println("Given array is");              // Printing the array before sorting    for(int i = 0; i < n; i++)    {        System.out.println(i+": "+arr[i]);    }    System.out.println();     selectionSort(arr, n);     System.out.println("Sorted array is");         // Printing the array after sorting    for(int i = 0; i < n; i++)    {        System.out.println(i+": "+arr[i]);    }}} /*This code is contributed by rajesh999*/
# Python program to implement Selection Sort for#  array of strings # Function defined for sorting the array of stringsdef Selection(arr,n):       # One by one move boundary of unsorted subarray    for i in range(n):        min_index = i        min_str = arr[i]                 # Find the minimum element in unsorted subarray        for j in range(i+1,n):                         # If min_str is greater than arr[j]            if min_str>arr[j]:                                 # Make arr[j] as min_str and update min_index as j                min_str = arr[j]                min_index = j                         # Swap the found minimum element with the first element              if min_index != i:                         # Store the first element in temp            temp = arr[i]                         # Place the min element at the first position            arr[i] = arr[min_index]                         # place the element in temp at min_index            arr[min_index] = temp          # Return the sorted array    return arr arr = ["GeeksforGeeks", "Practice.GeeksforGeeks", "GeeksQuiz"] print("Given array is")for i in range(len(arr)):    print(i,":",arr[i]) print("\nSorted array is")for i in range(len(Selection(arr,len(arr)))):    print(i,":",Selection(arr,len(arr))[i])             # This code is contributed by Manish KC# profile: mkumarchaudhary06
// C# program to implement selection sort// on array of stringsusing System; class GFG{     // Sorts an array of stringsstatic void selectionSort(string[] arr, int n){         // One by one move boundary of    // unsorted subarray    for(int i = 0; i < n - 1; i++)    {                 // Find the minimum element in        // unsorted array        int min_index = i;        string minStr = arr[i];                 for(int j = i + 1; j < n; j++)         {                           /*compareTo() will return a -ve value,             if string1 (arr[j]) is smaller than            string2 (minStr)*/            // If arr[j] is smaller than minStr                       if (arr[j].CompareTo(minStr) != 0)             {                                  // Make arr[j] as minStr and                // update min_idx                minStr = arr[j];                min_index = j;            }        }           // Swapping the minimum element         // found with the first element.        if (min_index != i)        {            string temp = arr[min_index];            arr[min_index] = arr[i];             arr[i] = temp;         }    }} // Driver Codestatic void Main(){    string[] arr = { "GeeksforGeeks",                      "Practice.GeeksforGeeks",                      "GeeksQuiz" };    int n = arr.Length;    Console.WriteLine("Given array is");                // Printing the array before sorting    for(int i = 0; i < n; i++)    {        Console.WriteLine(i + ": " + arr[i]);    }    Console.WriteLine();         selectionSort(arr, n);         Console.WriteLine("Sorted array is");           // Printing the array after sorting    for(int i = 0; i < n; i++)    {        Console.WriteLine(i + ": " + arr[i]);    }}} // This code is contributed by divyesh072019
<script>    // Javascript program to implement selection sort on array of strings         // Sorts an array of strings    function selectionSort(arr, n)    {         // One by one move boundary of        // unsorted subarray        for(let i = 0; i < n - 1; i++)        {             // Find the minimum element in            // unsorted array            let min_index = i;            let minStr = arr[i];             for(let j = i + 1; j < n; j++)            {                 /*compareTo() will return a -ve value,                if string1 (arr[j]) is smaller than                string2 (minStr)*/                // If arr[j] is smaller than minStr                 if ((arr[j]).localeCompare(minStr) === -1)                {                     // Make arr[j] as minStr and                    // update min_idx                    minStr = arr[j];                    min_index = j;                }            }             // Swapping the minimum element            // found with the first element.            if (min_index != i)            {                let temp = arr[min_index];                arr[min_index] = arr[i];                arr[i] = temp;            }        }    }         let arr = [ "GeeksforGeeks",                     "Practice.GeeksforGeeks",                     "GeeksQuiz" ];    let n = arr.length;    document.write("Given array is" + "</br>");                 // Printing the array before sorting    for(let i = 0; i < n; i++)    {        document.write(i + ": " + arr[i] + "</br>");    }    document.write("</br>");          selectionSort(arr, n);          document.write("Sorted array is" + "</br>");            // Printing the array after sorting    for(let i = 0; i < n; i++)    {        document.write(i + ": " + arr[i] + "</br>");    }   // This code is contributed by vaibhavrabadiya117.</script>
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.
This article is contributed by Nikhil Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
 
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
 
rathbhupendra
mkumarchaudhary06
rajesh999
divyesh072019
vaibhavrabadiya117
sourabhbgp1994
tamanna17122007
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Longest Common Prefix using Sorting
Sort a nearly sorted (or K sorted) array
Segregate 0s and 1s in an array
Sorting in Java
Find whether an array is subset of another array
Quick Sort vs Merge Sort
Quickselect Algorithm
Stability in sorting algorithms
Find all triplets with zero sum