bubble sort syntax error (wrong Output)

/*
Design and develop a Bubble Sort program using two
different modular programming methods, i.e. pass-by-
value,
*/


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
using namespace std;
void display(int x);
void check_if(int n1, int n2);
int main()
{
    int i, j, pass = 0;
    int a[10] = { 100,33,49,23,84,2,72,17,82,64 };
    cout << "Input list ...\n";
    for (i = 0; i < 10; i++) {
    display(a[i]);
    }
    
    cout << endl;
    for (i = 0; i < 10; i++)
    {
        for (j = i + 1; j < 10; j++)
        {
            check_if(a[j], a[i]);
        }
        pass++;
    }
    cout << "Sorted Element List ...\n";
    for (i = 0; i < 10; i++) {
    display(a[i]);         // Output is wrong 
    }
    cout << "\nNumber of passes taken to sort the list:" << pass << endl;
	return 0;
}

void display(int x)
{ 
   cout << x << "\t";   
}

void check_if(int n1,int n2)
{
    int temp;

    if (n1 < n2)
    {
        temp = n2;
        n2 = n1;
        n1 = temp;
    }
}
Last edited on
Now is the time to brush up your debugging skills - or get to grips with it if you haven't used it before.

Using the debugger trace through the code and watch the contents of the variables. When it doesn't execute as expected from your design/algorithm then you have found an issue. Fix that and then repeat the debugging until the program works as expected.
hmm is it something wrong in this function?

1
2
3
4
5
6
7
8
9
10
11
void check_if(int n1,int n2)
{
    int temp;

    if (n1 < n2)
    {
        temp = n2;
        n2 = n1;
        n1 = temp;
    }
}


is that i need to use pass-by-references to solve this? something like passing the whole array instead of individual element?
Last edited on
but then if like this it become pass-by-references instead of pass-by-value.
Yes, if you want the changes in value for n1 and n2 to be reflected in the calling code, you need to pass them by reference.
Replace line 19 with
1
2
if (a[j] < a[i])
    std::swap(a[j], a[i]);


You need to include <utility>
Your sort logic is right.

Input list ...
100	33	49	23	84	2	72	17	82	64	
Sorted Element List ...
2	17	23	33	49	64	72	82	84	100	
Number of passes taken to sort the list:10

owwh I see. Thks again for helping me ^^.
Topic archived. No new replies allowed.