Sahat Yalkabov - 1 year ago 62

Java Question

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

In other words

`in`

But when it reaches

`out`

`out`

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

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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);
}
right--;
for (int pos = right; pos > left; pos--)
{
if (a[pos] < a[pos-1])
swap(pos, pos-1);
}
left++;
}
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**