public class SelSort2 { public static void main(String[] args) { double[] a = { 6.7, 2.3, 7.8, 3.4, 5.6, 4.5, 8.9 }; // 7 elements double[] b = { 6.7, 4.5, 9.9}; // Second array int i, j, min_j; // Array indices double help; // helper variable for 3-way exchange /* --------------------------------------------------- Print array before sorting --------------------------------------------------- */ for ( i = 0 ; i < a.length ; i++ ) { System.out.println( a[i] ); } /* --------------------------------------------------- The selection sort algorithm --------------------------------------------------- */ for ( i = 0 ; i < a.length ; i++ ) { /* --------------------------------------------------- Find array element with min. value among a[i], a[i+1], ..., a[n-1] --------------------------------------------------- */ min_j = i; // Assume elem i (a[i]) is the minimum for ( j = i+1 ; j < a.length ; j++ ) { if ( a[j] < a[min_j] ) { min_j = j; // We found a smaller minimum, update min_j } } /* --------------------------------------------------- Swap a[i] and a[min_j] --------------------------------------------------- */ help = a[i]; a[i] = a[min_j]; a[min_j] = help; } System.out.println( "Array after Selection Sort:"); /* --------------------------------------------------- Print array after sorting --------------------------------------------------- */ for ( i = 0 ; i < a.length ; i++ ) { System.out.println( a[i] ); } /* ============= Sort array b ================= */ System.out.println(); /* --------------------------------------------------- Print array before sorting --------------------------------------------------- */ for ( i = 0 ; i < b.length ; i ++ ) { System.out.println( b[i] ); } /* --------------------------------------------------- The selection sort algorithm --------------------------------------------------- */ for ( i = 0 ; i < b.length ; i++ ) { /* --------------------------------------------------- Find array element with min. value among b[i], b[i+1], ..., b[n-1] --------------------------------------------------- */ min_j = i; // Assume elem i (b[i]) is the minimum for ( j = min_j+1 ; j < b.length ; j++ ) { if ( b[j] < b[min_j] ) { min_j = j; // We found a smaller minimum, update min_j } } System.out.println("i = " + i + ", min-index = " + min_j ); /* --------------------------------------------------- Swap b[i] and b[min_j] --------------------------------------------------- */ help = b[i]; b[i] = b[min_j]; b[min_j] = help; } System.out.println( "Array after Selection Sort:"); /* --------------------------------------------------- Print array after sorting --------------------------------------------------- */ for ( i = 0 ; i < b.length ; i ++ ) { System.out.println( b[i] ); } } }