0

I wrote bubble sort algorithm for my class project. I tried using an array and it works fine as I expected. Then I tried to sort a vector using the same algorithm and it doesn't work. any help would be appreciated, thanks!

here's the code using an array :

#include <iostream>

void bubble_sort(int arr[], size_t arr_size){
    for (size_t i = 0; i < (arr_size - 1); i++) {
        for (size_t j = 0; j < (arr_size - i - 1); j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void print_arr(int arr[], size_t arr_size) {
    for (size_t i = 0; i < arr_size; i++) {
        std::cout << arr[i] << " ";
    }
}

int main(){
    int arr[] = {2, 1, 5, 3, 4};
    std::cout << "unsorted : ";
    print_arr(arr, 5);
    bubble_sort(arr, 5);
    std::cout << "\nsorted : ";
    print_arr(arr, 5);
    return 0;
}

using a vector :

#include <iostream>
#include <vector>

void bubble_sort(std::vector <int> arr){
    for (size_t i = 0; i < (arr.size() - 1); i++) {
        for (size_t j = 0; j < (arr.size() - i - 1); j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

void print_arr(std::vector <int> arr) {
    for (size_t i = 0; i < arr.size(); i++) {
        std::cout << arr[i] << " ";
    }
}

int main(){
    std::vector <int> arr = {2, 1, 5, 3, 4};
    std::cout << "unsorted : ";
    print_arr(arr);
    bubble_sort(arr);
    std::cout << "\nsorted : ";
    print_arr(arr);
    return 0;
}
Joe
  • 1
  • 2
    `void bubble_sort(std::vector arr){` creates a copy of the vector and the function sorts the copy. Pass the vector by reference: `void bubble_sort(std::vector &arr){`. – Thomas Sablik Mar 29 '23 at 17:35
  • Note: Arrays pass by reference unless you take heroic steps to prevent it. See [What is array to pointer decay?](https://stackoverflow.com/q/1461432/4581301) for details. This is why the array version works without explicitly passing by reference. – user4581301 Mar 29 '23 at 17:54
  • If you had called `print_arr` inside of the `bubble_sort` function, after the nested `for` loops, you would have seen that [arr is sorted](https://godbolt.org/z/nrWv57zeq). The issue that others have pointed out is that `bubble_sort` sorted a copy of the array, and not the actual array from `main`. – PaulMcKenzie Mar 29 '23 at 18:12

0 Answers0