Answer to Question #53184 in C++ for jemal

Question #53184
Define a function to input a list of names and store them as dynamically-allocated strings in an array,
and a function to output them:
void ReadNames (char *names[], const int size);
void WriteNames (char *names[], const int size);
Write another function which sorts the list using bubble sort:
void BubbleSort (char *names[], const int size);
Bubble sort involves repeated scans of the list, where during each scan adjacent items are compared
and swapped if out of order. A scan which involves no swapping indicates that the list is sorted.
1
Expert's answer
2015-07-03T03:10:04-0400
#include <iostream>

using namespace std;

// The function prototypes
void ReadNames(char *names[], const int size);
void WriteNames(char *names[], const int size);
void BubbleSort(char *names[], const int size);

int main()
{
char *names[4];

ReadNames(names, 4);
BubbleSort(names, 4);
WriteNames(names, 4);

// To pause
cin.get();
cin.get();

return 0;
}



void ReadNames(char *names[], const int size)
{
char name[128];

for (int i = 0; i < size; i++)
{
cout << "names[" << i << "] = ";
cin >> name;
names[i] = new char[strlen(name) + 1];
strcpy_s(names[i], strlen(name) + 1, name);
}
}

void WriteNames(char *names[], const int size)
{
for (int i = 0; i < size; i++)
{
cout << names[i] << '\n';
}

}

void BubbleSort(char *names[], const int size)
{
bool sw;
char *temp;

// Sort
for (int i = size; i > 0; i--)
{
sw = true;
for (int j = 1; j < i; j++)
{
if (strcmp(names[j], names[j - 1]) > 0 )
{
temp = names[j];
names[j] = names[j - 1];
names[j - 1] = temp;
sw = false;
}
}
// A scan which involves no swapping indicates that the list is sorted.
if (sw)
{
break;
}

}

}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS