kianhun4167 chai
kianhun4167 chai

Reputation: 17

My c++ Bubble sort function is not working

I need to create a function called bubbleSort by passing the value instead of passing an array. But the bubbleSort function doesn't work at all. It still output the unsorted numbers which is the one that I assign to the only array in main(). The result should be shown as ascending order.

#include <iostream>

using namespace std;
void bubbleSort(int, int);

int main(){   
    const int size = 10;
    int numbers[size] = { 100, 33, 49, 23, 84, 2, 72, 17, 82, 64 };

    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }

    for (int i = 0; i < size; i++) {
        for (int j = i+1; j < size; j++) {
            bubbleSort(numbers[i], numbers[j]);
        }
    }
    cout << "\n";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

void bubbleSort(int i, int j) {
    int temp;
    if (i > j) {
        temp = i;
        i = j;
        j = temp;
    }
}

the result is shown like this

100 33 49 23 84 2 72 17 82 64
100 33 49 23 84 2 72 17 82 64

Upvotes: 0

Views: 184

Answers (1)

Omid Talebi
Omid Talebi

Reputation: 17

You must pass the parameter function of your Babel sort function to the function as a call-by-reference to be applied to the array you defined in the mine after completing the operation function.

like under :

#include <iostream>

using namespace std;
void bubbleSort(int&, int&);

int main()
{
    const int size = 10;
    int numbers[size] = { 100, 33, 49, 23, 84, 2, 72, 17, 82, 64 };

    for (int i = 0; i < size; i++)
    {
        cout << numbers[i] << " ";
    }

    for (int i = 0; i < size; i++)
    {
        for (int j = i+1; j < size; j++)
        {
            bubbleSort(numbers[i], numbers[j]);
        }
    }
    cout << "\n";
    for (int i = 0; i < size; i++) {
        cout << numbers[i] << " ";
    }
    return 0;
}

void bubbleSort(int &i, int &j) {
    int temp;
    if (i > j) {
        temp = i;
        i = j;
        j = temp;
    }
}

for example:
input :  100 33 49 23 84 2 72 17 82 64
out put :  2 17 23 33 49 64 72 82 84 100

For further reading, you can refer to the following site. https://www.tutorialspoint.com/cplusplus/cpp_function_call_by_reference.htm

Upvotes: 1

Related Questions