Dear fellows I'm facing a problem in this program I tried to rectify the mistake a lot but all in vain.. The result of this program shows an extra line of 1(like 1 1 1 1 1 1 ) at the end of the result ..can someone tell me from where this line comes???
#include <iostream.h>
#include <stdlib.h>
void swap(int *, int *) ;
main(){
int x [] = {1,3,5,7,9,2,4,6,8,10}; // x[0]=1
int i, j, tmp, swaps;
for(i = 0; i < 10; i ++){
swaps = 0;
for(j = 0; j < 10; j ++){
// compare two values and interchange if needed
if ( x[j] > x[j+1]) // j=0 x[0] > x[1]
{
swaps++;
#include <iostream>
usingnamespace std;
void swap(int *, int *) ;
int main() // <- int main. You have to give it a return type!
{
int x [] = {1,3,5,7,9,2,4,6,8,10};
int i, j, swaps;
for(i = 0; i < 10; i ++)
{
swaps = 0;
for(j = 0; j < 9; j ++) // <-change to < 9...
{
// since you are doing x[j+1] here, if you allow j=9, then j+1 will be x[10] which is OUT OF BOUNDS
// this was resulting in stack corruption in your program and was causing weird results and runtime
// crashes when I ran it. You should stop the loop BEFORE j=9 that way the last 2 items you swap will
// be [8] and [9]
if ( x[j] > x[j+1] )
{
swaps++;
swap(&x[j],&x[j+1]);
}
}
if (swaps == 0) break; // I put this in the 'i' outer loop rather than the 'j' inner loop
// now you'll actually stop sorting when swaps==0
for (j=0; j<10; j++)
{
cout << x[j] << ' '; // <- I changed the \t to a space so the output was easier to see
// if (swaps == 0) break; // <- this was causing your mysterious row of 1's. What was happening
// was when the array was sorted, swaps was zero. So in this print loop you would print the first
// item (1), then exit the loop -- but you WOULDN'T exit the outer loop (the 'i' loop). So you would
// keep printing the first element over and over.
}
cout << '\n'; // I added this to make the output more clear
}
int stop ;
cin>>stop;
}
void swap(int *x, int *y)
{
int tmp;
// if(*x > *y) // <- I don't know why you were doing this here. You shouldn't be.
// swap should only swap whatever it was given. It shouldn't care which is larger.
{
tmp = *x;
*x = *y;
*y = tmp;
}//if
}