Hey guys I am taking Mosh’s C++ course part 2 and I need help with this bubble sort algorithm.
// Online C++ compiler to run C++ program online
#include <iostream>
using namespace std;
int swap(int a, int b){
int temp = a;
a = b;
b = temp;
return 0;
}
int bubble_sort(int numbers[], int size){
for (int i = 1; i < size; i++){
if (numbers[i] < numbers[i - 1]){
swap(numbers[i], numbers[i - 1]);
}
}
return 0;
}
int main() {
int numbers[] = {30, 10, 20}; // 0, 1, 2
bubble_sort(numbers, size(numbers));
for (int i = 0; i < size(numbers); i++)
cout << numbers[i];
return 0;
}
As you can see in my code, there might be errors when you run it. But that is not the problem because programmers make small mistakes. So anyway, my problem is the swap function which is supposed to do the three buckets thing which swaps 2 variables. Mosh used these parameters “(int numbers, int i, int j)”, and i tried to use another implementation. But it seems to not work. Can you please tell me a solution to this?
The problem here is that your swap function declaration accepts its values as parameters:
swap(int a, int b) …
Your calling function is extracting values from the array and passing them into your swap function by value:
swap(numbers[i], numbers[i - 1]);
So what you’re basically doing here is passing a copy of those integers to your swap function, which then exist as local function variables on the stack. Your function is still comparing two integers, but it’s swapping the value of these copies, not the values in the original array. And when the swap function returns, those values get discarded.
The swap function needs to modify the values in the original array, either by accessing that array itself directly or by having it also passed in as a parameter as Mosh did in the original code.
Yes! The return type really makes a difference. In your implementation, you have used integer return type for swap and bubble_sort functions which is not necessory. The reason is that you are not returning any integer value from those two functions to the places from where those functions was called. Instead, you are working in the array itself in those two functions. Hence, these two function is implemented solely with purpose of making some changes in the array and not to return any values from those functions.
This is the reason why you have to pass array as argument to those two function in order to execute the bubble sort operation because the bubble sort operation is taken place in the array itself. If you don’t pass the array as argument, the array will not be rearranged in chronological order.
So, if you are not returning any value from a function, it is better to go with void() function because this function returns nothing!. It just executes the code written in it’s body.