Web Hosting Talk







View Full Version : Programming Help - Bubble Sort


CresHost
06-10-2007, 07:35 AM
Hello,

I am implementing Bubble Sort and File Writing as an Assignment . I am having a problem . This is the function for the Bubble Sort I have written:

void BubbleSort()
{
ifstream input;
input.open("input.txt");
int temp[MAX];
int count=0;
while (!input.eof())
{
int t;
input>>t;
temp[count]=t;
count++;
}

input.close();

for (int i=0;i<(count-1);i++)
{
for (int j=(count-1);j>i;j--)
{
if (temp[j]<temp[j-1])
{
int tempswap;
tempswap=temp[j];
temp[j]=temp[j-1];
temp[j-1]=tempswap;
}
}
}

ofstream bubble;
bubble.open("bubble.txt", ios::app);

for (int i=0;i<(count-1);i++)
{
bubble<<temp[i]<<endl;
}

bubble.close();

}

The problem is that by running the program suppose I enter in the exact same order:

5
2
7
21
9
1

in the input.txt file , when i call the bubble sort function above.

The output in bubble.txt is formed as:

1
1
2
5
7
9

I have been trying to solve it for few hours now cant figure it out . I have also made Selection sort and it is working perfectly fine.

Can anyone help me?

Thanks in advance.

SparkSupport
06-10-2007, 11:20 AM
i did a quick scan. i think you need to use i<=(count-1) whereever you have i<(count-1).

Suppose you have 6 items. After the first while loop, count gets the value 7. Then if you use i<(count-1), i takes values from 0 to 5 only.

CresHost
06-10-2007, 12:21 PM
i did a quick scan. i think you need to use i<=(count-1) whereever you have i<(count-1).

Suppose you have 6 items. After the first while loop, count gets the value 7. Then if you use i<(count-1), i takes values from 0 to 5 only.

Tried it , Doesnt work properly still.

It is showing an extra 1 which was never inputted and also not showing up 21 .

Codelphious
06-10-2007, 01:18 PM
ofstream bubble;
bubble.open("bubble.txt", ios::app);

for (int i=0;i<(count-1);i++)
{
bubble<<temp[i]<<endl;
}

bubble.close();

}

...
Should be...

for (int i=0;i<count;i++)
{
bubble<<temp[i]<<endl;
}

Since C uses 0 as the first index the last value in your array will have the index of count-1.

Just think about it this way. Say count = 3;

Is 0<3? Yes... print index 0.
Is 1<3? Yes... print index 1.
Is 2<3? Yes... print index 2.
Is 3<3? No... forget this index.

And you've printed 3 values. Hope this helped!