Rev 51 | Rev 53 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed
// Written by Ira Snyderimport java.io.*;class SortMethods {// method to sort the array a (passed as a parameter)// this will sort in O(n^2) timepublic static Object[] BubbleSort( Object[] a ) {//loop from the back of the array moving towards the beginningfor( int i=a.length-1; i>0; i-- )//loop from the beginning of the array to position "i"for( int j=0; j<i; j++ )//compare elements next to each other, and swap if necessaryif( a[j] > a[j+1] ) arraySwap(a,j,j+1);}public static Object[] ImprovedBubbleSort( Object[] a ) {boolean inorder=true;for( int i=a.length-1; i>0; i-- ) {inorder=true;for( int j=0; j<i; j++ )if( a[j] > a[j+1] ) {arraySwap(a,j,j+1);inorder=false;}if(inorder) break; //array sorted, so bail out}}// method to sort the array a (passed as a paramter)// this will sort in O(n^2) timepublic static Object[] SelectionSort( Object[] a ) {//loop from the back of the array moving towards the frontfor( int i=a.length-1; i>0; i-- ) {//placeholder for the maximum elementint m=0;//find the maximum element in the arrayfor( int j=1; j<=i; j++ )if( a[j] > a[m] ) m = j;//swap the "i"th element with the maximum elementarraySwap(a,i,m);}}// method to sort the array a (passed as a parameter)// this will sort in O(n^2) timepublic static Object[] InsertionSort( Object[] a ) {//iterate through the array from the beginning to the endfor ( int i=1; i<a.length; i++ ) {//store a[i] in a temp locationObject ai = a[i];int j=i; //start for the inner loop//find the place to insert ai, and shift elements downfor ( j=i; j>0 && a[j-1]>ai; j-- )a[j] = a[j-1]; //shift down//insert ai into position a[j]a[j] = ai;}}//ShellSort//MergeSort//HeapSort//QuickSortpublic static void arraySwap( Object[] a, int posA, int posB ) {Object temp = a[posB]; // temp = Ba[posB] = a[posA]; // B = Aa[posA] = temp; // A = temp}}