Search code examples
c++algorithmsortingbubble-sort

C++ Bubble Sort, how to ignore the same numbers


I'm using bubble sort to sort numbers in an array in order from lowest to highest. But there are some numbers which are the same, but I don't need them to be printed twice. So how do I check whether it was already printed and not to repeat the action?

The Bubble sort:

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

            if(m[i]>m[j]){
                temp=m[i];
                m[i]=m[j];
                m[j]=temp;
            }
        }
    }

Solution

  • Since number are already sorted when you are printing it, you can store the last printed number and compare against this before printing.

    Something like:

    std::cout << m[0] << std::endl;
    int last_print = m[0];
    
    for(int i = 1; i < n; ++i)
    {
      if(m[i] != last_print)
      {
        std::cout << m[i] << std::endl;
        last_print = m[i];
      }
    }