Sahat Yalkabov Sahat Yalkabov - 1 year ago 68
Java Question

Bidirectionnal Bubble Sort in Java?

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

In other words

will go from left to right first carrying the largest value.

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

I am advised to to implement another
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);

Answer Source
    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);

          for (int pos = right; pos > left; pos--)
             if (a[pos] < a[pos-1])
               swap(pos, pos-1);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download