Skip to content
Related Articles

Related Articles

Program to sort an array of strings using Selection Sort

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 08 Jun, 2022
Improve Article
Save Article

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;
        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 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




// 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_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;
        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 code
int 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




// Java program to implement selection sort
// on array of strings
import java.util.*;
import java.io.*;
 
class Main
{
     
// Sorts an array of strings
static 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 code
public 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*/

Python3




# Python program to implement Selection Sort for
#  array of strings
 
# Function defined for sorting the array of strings
def 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#




// C# program to implement selection sort
// on array of strings
using System;
 
class GFG{
     
// Sorts an array of strings
static 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 Code
static 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

Javascript




<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>

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.

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.

 


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!