Search code examples
javaalgorithmsortingbubble-sort

Bidirectionnal Bubble Sort in Java?


I need to implement the bidirectional bubble sort in my code.

In other words in will go from left to right first carrying the largest value.

But when it reaches out, it should reverse and go from right to left carrying the smallest value.

I am advised to to implement another out index in addition the current one.

This is what I have so far - just 2 loops. I am guessing I have to combine them somehow?

    public void bubbleSort() {
    int out, in; // nElems in my case is 4, because I have 4 elements in my array

    for(out=nElems-1; out>1; out--) // outer loop backward
        for(in=out; in>1; in--) // inner loop backward
            if(a[in] < a[in-1])
                swap(in, in-1);

    for(out=0; out<nElems; out++) // outer loop forward
        for(in=0; in<out; in++) // inner loop forward
            if(a[in] > a[in+1])
                swap(in, in+1); 

Solution

  •     public void bidirectionalBubbleSort()
        {
           int left = 0, right = a.length-1;
           while (left < right)
           {
              for (int pos = left; pos < right; pos++)
              {
                 if (a[pos] > a[pos+1])
                    swap(pos, pos+1);
              }
              right--;
    
    
              for (int pos = right; pos > left; pos--)
              {
                 if (a[pos] < a[pos-1])
                   swap(pos, pos-1);
              }
              left++;
           }
       }