ATTENTION: You are viewing a page formatted for mobile devices; to view the full web page, click HERE.

Other Software > Developer's Corner

two way bubble sort

(1/1)

h0meopathic:

--- Code: Java ---public static void bubble( int a[] )  {    boolean done = false;    int temp;        for( int forwardPass = 1; forwardPass < N && !done; forwardPass++ )    {      done = true;      for( int i = 0; i < N - forwardPass; i++ )      {        if( a[ i ] > a[ i + 1 ] )        {          temp = a[ i ];          a[ i ] = a[ i + 1 ];          a[ i + 1 ] = temp;                    if( a[ i ] < a[ i - 1 ] )            {              temp = a[ i ];              a[ i ] = a[ i - 1 ];              a[ i - 1 ] = temp;              done = false;            }                done = false;        }      }    }  }
I'm trying to write a method that will sort some values that I've put into an array.

The first "if" statement does a bubble sort forwards and I know that works. I'm trying to get the bubble sort to sort backwards after the forward pass and the 2nd "if" statement is my attempt at doing so.

It seems to me that the code provided would work accordingly but it doesn't. I tried commenting out the first "if" statement and the program stops working at the 2nd "if" statement. However, if nothing is commented out then the program sorts like it should so maybe I'm testing it wrong.

VideoInPicture:
You are accessing the array out of bounds when it hits the line
if ( a[ i ] < a[ i - 1 ] ) and you have i = 0

h0meopathic:

--- Code: C# ---public static void bubble( int a[] )  {    boolean done = false;    int temp;        for( int forwardPass = 1; forwardPass < N && !done; forwardPass++ )    {      done = true;      for( int i = 0; i < N - forwardPass; i++ )      {        if( a[ i ] > a[ i + 1 ] )        {          temp = a[ i ];          a[ i ] = a[ i + 1 ];          a[ i + 1 ] = temp;                   done = false;        }      }    }  }
Please don't give me the answer but help walk me through it.

This is the code that makes the bubble sort keep making forward passes though the array until done = true (all the values in the array are sorted in a lowest to highest value order).
I am confused to hell as to how to make the sort make a forward pass and at the end make a backward pass and then forward again until all the values are in order.
Basically I'm trying to come up with the best algorithm of sorting to sort in the least amount of time using a bubble sort method (the one list above).

Navigation

[0] Message Index

Go to full version