Search code examples
c++sortingbubble-sort

Showing sort simulation


I'm trying to show the simulation of this bubble sort and I used a function swapper that has reference values but when I try to print it after the swap it also prints out the memory address. How can I fix this?

void swapper(int &a, int &b) {
  int temp = a;
  a = b;
  b = temp;

  return;
}

int main(){

//Bubble sort

int arr[] = {-2, 45, 0, 11, -9};
int n = 5;


for(int step = 0; step < n-1; step++) {

  for(int i = 0; i < n; i++) {
    if(arr[i] > arr[i + 1])
       swapper(arr[i], arr[i + 1]);
  }

  for(int x = 0; x < n; x++)
      cout << arr[x] << " ";

  cout << endl;

}

Solution

  • Fixing the bugs

    Try this:

    #include <iostream>
    using namespace std;
    
    void swapper(int &a, int &b) {
      int temp = a;
      a = b;
      b = temp;
    
      return;
    }
    
    int main(){
    
        //Bubble sort
    
        int arr[] = {-2, 45, 0, 11, -9};
        int n = 5;
    
    
        for(int step = 0; step < n-1; step++) {
    
            for(int i = 0; i+1 < n; i++) {
                if(arr[i] > arr[i + 1])
                    swapper(arr[i], arr[i + 1]);
            }
    
            for(int x = 0; x < n; x++)
                cout << arr[x] << " ";
    
            cout << endl;
        }
    }
    

    I added a missing } and changed the condition of the inner loop to i+1 < n to avoid array access out of bounds.

    This is the output:

    -2 0 11 -9 45 
    -2 0 -9 11 45 
    -2 -9 0 11 45 
    -9 -2 0 11 45
    

    Aligning the output

    You can make the output aligned more nicely by replacing

    cout << arr[x] << " ";
    

    with

    cout << setw(2) << arr[x] << " ";
    

    and writing

    #include <iomanip>
    

    at the top of your file. Then the output is

    -2  0 11 -9 45 
    -2  0 -9 11 45 
    -2 -9  0 11 45 
    -9 -2  0 11 45