ghoot
ghoot

Reputation: 66

Bubblesort not working for some reason

I tried to write basic bubblesort in C++, and now I'm stuck. Any ideas why that might not work? I suppose it's obvious for more experienced people, but not for me.

liczba_liczb is number of array cells, niePosort is the array.

cout<<"\n\nRozpoczynam sortowanie:";
    for(int i=0;i<liczba_liczb-1;i++){  

        for(int j=0;j<liczba_liczb-1-i;j++){

            if(niePosort[j]>niePosort[j+1]){

                cout<<"\n"<<niePosort[j]<<">"<<niePosort[j+1]<<", zamiana.";

                temp = niePosort[j+1];
                niePosort[j+1]=niePosort[j];
                niePosort[j] = temp;
            }
        }

    }

Upvotes: 0

Views: 98

Answers (2)

Vlad from Moscow
Vlad from Moscow

Reputation: 310960

I do not understand what you mean saying that the code does not work. I tried it and it works. I only changed the array name for simplicity.

#include <iostream>

int main() 
{
   const size_t N = 10;
   int a[] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 };

   for ( size_t i = 0; i < N - 1; i++ )
   {  
      for ( size_t j = 0; j < N - 1 - i; j++ )
      {
         if ( a[j] > a[j+1] )
         {
            int temp = a[j+1];
            a[j+1] = a[j];
            a[j] = temp;
         }
      }
   }

   for ( int x : a ) std::cout << x << ' ';
   std::cout << std::endl;
}

The output is

0 1 2 3 4 5 6 7 8 9

That is the code sorts the array in the ascending order.

Upvotes: 1

ghoot
ghoot

Reputation: 66

It turned out that it was as simple as changing loops conditions to:

for(int i=0;i<liczba_liczb;i++)

for(int j=0;j<liczba_liczb-1-i;j++)

What was suggested by someone who, unfortunately, deleted his comment.

Upvotes: 0

Related Questions