Answer on Question #44587, Programming, C++
Problem.
write a function sort() to perform the sorting algorithm. But i don't know how to sort the names by alphabetical order. Thanks.
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
int main()
{
const int arraySize=20;
string name[arraySize]={"John","Catherine","Shelly","Zane","Ben","Tom","Albert","Melly","Danny","Jane","Elsa","Fiona","George"
<<"Harry","Idina","Kelly","Lance","Nandos","Patrick","Rose"};
int i,hold;
for(i=0;i<arraySize;i++)
{
for(int j=0;j<arraySize-i-1;j++)
{
if(name[j]>name[j+1])
{
hold=name[j];
name[j]=name[j+1];
name[j+1]=hold;
}
}
}
return 0;
}
}Solution.
The operators > and < are reloaded for string (see lexicographical_compare)
Code
#include<iostream>
#include<string>
using namespace std;
// sort() function
void sort(string name[], int arraySize) {
string hold;
}
// Print out values of array before sorting
cout << "Before sorting: " << endl;
for (int i = 0; i < arraySize; i++) {
cout << name[i] << " ";
if ((i + 1) % 10 == 0) {
cout << endl;
}
}
// Bubble sort
for (int i = 0; i < arraySize - 1; i++) {
for(int j = 0; j < arraySize - 1; j++) {
if(name[j] > name[j + 1]) { // the operators > and < are reloaded
for strings
// Swap two values
hold = name[j];
name[j] = name[j + 1];
name[j + 1] = hold;
}
}
}
// Print out values of array after sorting
cout << "After sorting: " << endl;
for (int i = 0; i < arraySize; i++) {
cout << name[i] << " ";
if ((i + 1) % 10 == 0) {
cout << endl;
}
}
return;
}
int main() {
const int arraySize = 20;
string name[arraySize] = {"John", "Catherine", "Shelly", "Zane", "Ben", "Tom", "Albert", "Melly", "Danny", "Jane", "Elsa", "Fiona", "George", "Harry", "Idina", "Kelly", "Lance", "Nandos", "Patrick", "Rose"};
sort(name, arraySize);
return 0;
}Result
Before sorting:
John Catherine Shelly Zane Ben Tom Albert Melly Danny Jane
Elsa Fiona George Harry Idina Kelly Lance Mandos Patrick Rose
After sorting:
Albert Ben Catherine Danny Elsa Fiona George Harry Idina Jane
John Kelly Lance Melly Mandos Patrick Rose Shelly Tom Zane
Process returned 0 (0x0) execution time : 0.102 s
Press any key to continue.
http://www.AssignmentExpert.com/
Comments