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.
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.
