OOP bubble sort


#include <iostream.h>
#include <string.h>
#include <stdlib.h>

void bubblesort(char *name[], int size);
void display (char*name[],int size);


int main()
{
int i, size;
char temp[80];
char **name;


cout<<"Please enter the number of names you want to enter = ";
cin>>size;
cin.ignore(3,'\n');
cout<<endl;

name = new char *[size];

for (i = 0; i<size; i++)
{
cout<<"Please enter name "<<i+1<<": ";
cin.getline(temp,80,'\n');
name[i]=new char[strlen(temp)+1];

strcpy(name[i],temp);
}

cout<<endl;

display(name,size);

bubblesort(name,size);

system("cls");

display(name,size);

system("pause");
return 0;
}

void bubblesort(char *name[], int size)
{
int i,sort = 0;
char temp[80];

do
{
for(i =0; i<size; i++)
{
if ( strcmp(name[i],name[i+1]) >0 )
{
strcpy(temp, name[i]);
strcpy(name[i],name[i+1]);
strcpy(name[i+1],temp);
sort++;
}

}
}while(sort!=0);
}

void display (char* name[],int size)
{
for (int i = 0; i<size; i++)
{
cout<<"Name "<<i+1<<" : "<<name[i]<<endl;
}
}

No error when compile and execute. but program crashed when passing through bubble sort function.
It could be that is because of "i<size".
Few lines below you use [i+1] so on the last loop i+1 is not < size.
You are accessing uninitialized pointer.
Make it "i<size-1"
In your for inside the do while, i will at one point ==size. At that point, during strcmp(), you'll be dereferencing name[i+1], causing a segmentation fault.
for (i =0; i<size-1; i++)

and

while (sort!=0,sort=0);
Last edited on
while (sort!=0,sort=0);
You don't know what that does, do you?
ermm, if i put i<size-1, then my last name will not be sorted
Yes, it will.
okay. i made the change, but the names are still not sorted. the program just stopped when it display the names entered.
oh my mistake again..

sort=0; on top of for (i =0; i<size-1; i++)

then

while (sort!=0);

that should work now..
OH great. It works.
thank a lot!

i made a really silly mistake. heehee. thanks a lot :DD
Topic archived. No new replies allowed.