Sahat Yalkabov - 5 months ago 26

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

Answer

```
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++;
}
}
```