Sort an Array of string using Selection sort in C++


The Selection Sort algorithm sorts an exhibit by more than once finding the base component from the unsorted part and putting it toward the start. In each emphasis of determination sort, the base component from the unsorted subarray is picked and moved to the arranged subarray.

Example

 Live Demo

#include <iostream>
#include <string.h>
using namespace std;
#define MAX_LEN 50
void selectionSort(char arr[][50], int n){
   int i, j, mIndex;
   // Move boundary of unsorted subarray one by one
   char minStr[50];
   for (i = 0; i < n-1; i++){
      // Determine minimum element in unsorted array
      int mIndex = i;
      strcpy(minStr, arr[i]);
      for (j = i + 1; j < n; j++){
         // check whether the 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]);
            mIndex = j;
         }
      }
      // Swap the minimum with the first element
      if (mIndex != i){
         char temp[50];
         strcpy(temp, arr[i]); //swap item[pos] and item[i]
         strcpy(arr[i], arr[mIndex]);
         strcpy(arr[mIndex], temp);
      }
   }
}
int main(){
   char arr[][50] = {"Tom", "Boyaka", "Matt" ,"Luke"};
   int n = sizeof(arr)/sizeof(arr[0]);
   int i;
   cout<<"Given String is:: Tom, Boyaka, Matt, Luke\n";
   selectionSort(arr, n);
   cout << "\nSelection Sorted is::\n";
   for (i = 0; i < n; i++)
      cout << i << ": " << arr[i] << endl;
   return 0;
}

This above C++ program initially chooses the smallest component in the exhibit and swaps it with the principal component in the cluster. Next, it swaps the second littlest component in the cluster with the subsequent component, etc. In this manner for each pass, the smallest component in the exhibit is chosen and put in its legitimate situation until the whole cluster is arranged. Finally, the section sort method sorts the given string in ascending order as follows;

Output

Given string is:: Tom, Boyaka, Matt, Luke
Selection Sorted::
Boyaka
Luke
Matt
Tom

Updated on: 23-Dec-2019

870 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements