You are on page 1of 2

Another example of the bubble sort with the 2-dim on the sort column.

You will have to copy the swap code and make it work for the other columns in both arrays. //Begin bubble sort int temp1 = 0; // As the loop count grows, the int n = codeArray.length; for (int swapPass=1; swapPass < { // the inner compare area gets for (int i=0; i < n-swapPass; { inner count shrinks n; swapPass++) smaller as the outter gets bigger i++)

if (codeArray[i][0] > codeArray[i+1][0]) { //decide which is larger // Swap for column1 in codeArray do the same for the rest temp = codeArray[i][0]; codeArray[i][0] = codeArray[i+1][0]; codeArray[i+1][0] = temp; }//end if statements }// end inner loop }// end outer loop

CompareTo
Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. The String method compareTo( ) serves this purpose. It has this general form: int compareTo(String str) Here, str is the String being compared with the invoking String. The result of the comparison is returned and is interpreted as shown here:

Value Less than zero

Meaning The invoking string is less than str.

Greater than zero Zero

T he invoking string is greater than str. The two strings are equal.

Here is a sample program that sorts an array of strings. The program uses compareTo( ) to determine sort ordering for a bubble sort: // A bubble sort for Strings. class SortString { static String arr[] = { "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "their", "country" }; public static void main(String args[]) { for(int j = 0; j < arr.length; j++) { for(int i = j + 1; i < arr.length; i++) { if(arr[i].compareTo(arr[j]) < 0) { String t = arr[j]; arr[j] = arr[i]; arr[i] = t; } } System.out.println(arr[j]); } } }

You might also like