Program to sort an array of strings using Selection Sort

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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


C

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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

chevron_right



Output :

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

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

This article is contributed by Nikhil Rawat. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :


8


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.