0

The problem I have getting 5 names from the user and displaying them in alphabetical order. This is my code. When debugging the problem seems to be in the sorted function. It is supposed to tell me when the array is fully sorted. Can someone tell me where my problem is. Thanks

 #include<iostream>
#include<string>
using namespace std;
void swap(string,string);
bool sorted (string [3]);

void main ()
{
    string firstname[3];
    string sortfirstname[3];
    int orginialindex[3];
    string lastname[3];
    float gpa[3];
    int id[3];
    for (int i=0;i<3;i++)
    {
    cout<<"Enter firstname"<<endl;
    cin>>firstname[i];
    }
    for (int i=0;i<3;i++)
    {
        sortfirstname[i]=firstname[i];
    }
    while (!(sorted(sortfirstname)))
    {
    for (int i=0;i<3;i++) //3-2-1
    {
        if (sortfirstname[i]>sortfirstname[i+1])
        {
            swap(sortfirstname[i],sortfirstname[i+1]);
        }
    }
    }
    cout<<sortfirstname[0]<<sortfirstname[1]<<sortfirstname[2];
}

void swap (string a, string b)
{
    string temp = b;
    b = a;
    a = temp;
}

bool sorted (string sortfirstname[3])
{
    bool sort;
    for (int i=0;i<3;i++)
    {
        if (sortfirstname[i]<sortfirstname[i+1])
            sort = true;
        else
            sort = false;
    }
    return sort;
}
NPE
  • 486,780
  • 108
  • 951
  • 1,012
Ahmed Abdelaal
  • 15
  • 1
  • 2
  • 5

2 Answers2

1

Your swap is wrong.

void swap (string a, string b)
{
    string temp = b;
    b = a;
    a = temp;
}

This wont do anything!! You need to be taking reference arguments, ie cahnge the function signature to:

void swap (string& a, string& b)

Also, bool sorted (string sortfirstname[3]) has errors, try:

bool sorted (string sortfirstname[3]) {
    bool sort = true;
    for (int i=0;i<3-1;i++)
    {
        if (sortfirstname[i]>sortfirstname[i+1])
            sort = false;
    }
    return sort;
}

this correct 2 things. (a) you ran over end before, (b) you decided whether they were sorted exclusively on last test.

RichardPlunkett
  • 2,998
  • 14
  • 14
0

The for cycle exit condition should be i<3-1 because later you are accessing (i+1)-th element.

HAL9000
  • 3,562
  • 3
  • 25
  • 47