Friday, September 23, 2011

Sorting

Bubble Sort


public class BubbleSort {

/**
* @param args
*/
public static void main(String[] args) {

int[] bsort = new int[] { 6, 10, 9, 2, 7, 4, 8, 1, 5, 3 };
// OR we can use int [] bsort={6,10,9,2,7,4,8,1,5,3,};

int i, j;

for (j = 0; j < bsort.length; j++) { // (length -1) cycles of sorting
for (i = 1; i < ((bsort.length) - j); i++) {                         // =1 cycle of sorting
// -j to optimise the cycle because in later cycle last few
// element need not be sorted(see the animaton above)
if (bsort[i - 1] > bsort[i]) // a[0] [1] compare
{
int temp = 0;                  // suggestion given by system to initialize
// temp with 0
temp = bsort[i - 1];       // Swapping will start from here
bsort[i - 1] = bsort[i];
bsort[i] = temp;

}
// else portion will not needed because,
// bsort[i - 1] <= bsort[i] remain as it is,and we have to move
// forward without changing anything, which will be done by i++

}
}

System.out.print(bsort[0] + ",");
System.out.print(bsort[1] + ",");
System.out.print(bsort[2] + ",");
System.out.print(bsort[3] + ",");
System.out.print(bsort[4] + ",");
System.out.print(bsort[5] + ",");
System.out.print(bsort[6] + ",");
System.out.print(bsort[7] + ",");
System.out.print(bsort[8] + ",");
System.out.print(bsort[9]);

}

}




No comments:

Post a Comment