I would need some help because I've been wondering about this algorithm for all day long now...So, basically I want to create a function that takes in input a string array and the number of elements and I want to arrange everything in order...but sometimes it works, sometimes not... It would be much appreciated if you can help me...I don't need to use any or something, just the basic string (NOT array of chars) and it's functions... Thank you!
#include <iostream>
#include <string>
#include <string.h>
#include <sstream>
#include <ctype.h>
bool sortS(string a ,string b)
{
for(int i=0;i<a.length() && i<b.length();i++)
{
if(a.substr(i,1)>b.substr(i,1))return false;
}
return true;
}
void selectionSort(string arr[], int n)
{
int i, j, min_idx;
for (i = 0; i < n-1; i++)
{
min_idx = i;
for (j = i+1; j < n; j++)
{
if (sortS(arr[j],arr[min_idx]))
{
min_idx = j;
}
swap(arr[min_idx], arr[i]);
}
}
}
int main()
{
string vett[]={"Junie","Andy","Laine","Buford","Kathrin","Slyvia","Earlean","Lakeshia","Marry","Arica"};
int n=sizeof(vett)/sizeof(vett[0]);
for(int i=0;i<n;i++)
{
cout<<vett[i]<<" ";
}
cout<<endl;
selectionSort(vett,n);
for(int i=0;i<n;i++)
{
cout<<vett[i]<<endl;
}
cout<<endl;
return 0;
}
The output is this:
Arica
Andy
Laine
Buford
Kathrin
Slyvia
Earlean
Lakeshia
Marry
Junie