Simple Sorting of an Array Algirthmn: Hello guys, I'm new to Java and could use some pointers (get it? Because Java doesn't explicitly have pointer....) Anyways, I'm trying to use the compareTo() function to compare the currentArrayIndex to the nextArrayIndex. For some reason when creating my tempArray as a placeholder while swapping the two indexes being compared the array just gets populated with the first index... Any ideas?
int max = 10; String[] arr = new String[max]; //a new arr object of Strings arr[0] = "B"; arr[1] = "A"; arr[2] = "C"; System.out.println(Arrays.toString(arr)); int i = 0; while(arr[i].compareTo(arr[i+1]) > 0){ //while the current arr index is out of order swap the two arrays String[] tempString = new String[2]; //arr [B][A][C][NULL] tempString[0] = arr[i]; //tempString--->[B][][] arr[B][A][C] //value int results = arr[i].compareTo(arr[i+1]); System.out.println(results); tempString[1] = arr[i++]; //tempString--->[B][A][] arr[B][A][C] arr[i] = tempString[1]; //tempString--->[B][A][] arr[A][A][C] arr[i+1] = tempString[0]; //tempString--->[B][A][] arr[A][B][C] DONE SORTING i++; tempString = null;//clear the array System.out.println(Arrays.toString(arr)); }
tempString[1] = arr[i++]; //tempString--->[B][A][] Auto post incrementing an array index this way can have surprising results. In this line of code, i is evaluated, and that value is used and then i is incremented.
Ugh I thought i got rid of that i++ in that array index, Thank you for pointing that out to me rsmith6559.... It's sorted now
Join our real-time social learning platform and learn together with your friends!