Write a version of the selection sort algorithm that can be used to sort a list of strings alphabetically. (Selection sort for int lists is discussed in Chapter 8.) Write a program to test the function and prompt the user to enter 10 strings. Output the sorted list to the console. *Need answer in C++*
//Write a program to implement selection sort for strings.
#include<iostream.h>
#include<conio.h>
#include<string.h>
#define MAX_LENGTH 80
//length of all string should be smaller than MAX_LENGTH
void selection_Sort(char array[][MAX_LENGTH], int num) //function
definition
{
int i, j, min_idx;
char minString[MAX_LENGTH];
for (i = 0; i < num-1; i++)
{
// Find the smallest element in unsorted array
int min_idx = i;
strcpy(minString, array[i]); //copy the contents of
array[i] to minString
for (j = i + 1; j < num; j++)
{
// If minimum is greater than array[j]
if (strcmp(minString, array[j]) > 0) //compare both
the strings character by character
{
// Make array[j] as minString and
update the value of min_idx
strcpy(minString, array[j]);
min_idx = j;
}
}
// Interchange the found minimum element with the 1st
element
if (min_idx != i)
{
char temp[MAX_LENGTH];
strcpy(temp, array[i]); //Interchange item[position]
and item[i]
strcpy(array[i], array[min_idx]);
strcpy(array[min_idx], temp);
}
}
}
void main()
{
char array[10][MAX_LENGTH];
int i,num =10;
clrscr();
for (i = 0; i < num; i++)
{
cout<<"Enter the
string:"<<i+1<<"=";
cin>>array[i]; //accept 10 strings from
user
}
selection_Sort(array, num); //calling selection_Sort function
cout << "\nSorted array is\n";
for (i = 0; i < num; i++)
cout << i+1 << ": " << array[i]
<< endl; //display sorted array
getch();
}
Output:
Screenshots of the program:
Please give positive rating.
Get Answers For Free
Most questions answered within 1 hours.