Bubble sort strings from a 2D array.
Oct 30, 2014 at 11:56pm UTC
Hello,
I have a project where I have to create a Bubble sort that will ask the user to input names and then print the names out, sort them, and print them out sorted.
I have almost everything down, but the strings just don't sort. I am using strcmp and strcpy. But the names just don't move at all. Please help, I do not know what to do.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#include <iostream>
#include <string.h>
#include "ReadFunctions.h"
#include "Sorting.h"
using namespace std;
char BubbleSort(char Names [] [MaxLetters], int NumElements);
int main()
{
const int MaxNames(20);
const int MaxLetters(15);
char Names [MaxNames + 1] [MaxLetters + 1];
int NumRows;
int Row;
int NumCols = MaxLetters;
int x;
cout << "How many names shall you enter?" << endl;
NumRows = ReadInteger ();
cout << "Enter " << NumRows << " names: " << endl;
for (Row = 0; Row < NumRows; Row++)
{
cin.getline (Names [Row], MaxLetters + 1, '\n' );
}
cout << "You entered " << endl;
for (Row = 0; Row < NumRows; Row++)
{
cout << Names[Row];
cout << endl;
}
for (x = 0; x < NumRows; x++)
{
BubbleSort (Names, NumRows);
cout << "\t" << Names [x] << endl;
}
}
and here is the Bubble sort code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
char BubbleSort(char SortNames[][MaxLetters], int NumElements)
{
const int MaxNames(20);
int i = 0;
bool Sorted = true ;
char Temp [MaxNames + 1];
int Result;
do {
for (i = 0; i < MaxNames; i++)
{
Result = (strcmp(SortNames[i], SortNames[i + 1]) != 0);
if (Result < 0)
{
Sorted = false ;
strcpy(Temp, SortNames[i]);
strcpy(SortNames[i], SortNames[i + 1]);
strcpy(SortNames[i + 1], Temp);
}
else ;
}
} while (!Sorted);
return (SortNames, NumElements);
}
Topic archived. No new replies allowed.