Friday, August 31, 2012

Bi-directional bubble sort Algorithmn in java ?


public class BidirectionalBubbleSort {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };

System.out.println("Values Before the sort:\n");
for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

System.out.println();

bidirectionalBubble_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

}

public static void bidirectionalBubble_srt(int array[], int n) {
int j;
int st = -1;
while (st < n) {
st++;
n--;
for (j = st; j < n; j++) {
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
}
for (j = n; --j >= st;) {
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
}
}
}
}


Values Before the sort:

12  9  4  99  120  1  3  10

Values after the sort:

1  3  4  9  10  12  99  120

No comments:

Post a Comment