user6882864
user6882864

Reputation:

How can I find why my bubble sort doesn't work?

I am trying to learn Bubble Sort algorithm. Most of the code on the internet are using Boolean variable, but I want to do this without Boolean.

# include <iostream>
using namespace std;

int main ()
{
    int n;
    int k;
    int temp;
    int arr[6] = {9,7,8,6,4,2};

    for(n=0;n<6;n++){
        for(k=0;k<n-1;k++){
            if(arr[k]>arr[k+1]){
                temp = arr[k+1];
                arr[k+1]=arr[n];
                arr[k] = temp;
            }
        }
    }
    for(n=0;n<6;n++){
        cout<< arr[n] << endl;
    }

}

Upvotes: 0

Views: 233

Answers (1)

Geeky
Geeky

Reputation: 7496

Change your code to:

for(n=0;n<6;n++){
        for(k=0;k<5;k++){
            if(arr[k]>arr[k+1]){
                temp = arr[k];
                arr[k]=arr[k+1];
                arr[k+1] = temp;
            }
        }
    }

Your logic will never work because:

  1. when n=0, your k=0 and you're checking k<-1 it's not, so the following loop won't run
  2. when n=1, your k starts from 0 and k<0 it's not, so the following loop never works

Upvotes: 3

Related Questions