One mistake I made on my sort lab that took me forever to figure out was the < vs. > sign when comparing two different arrays. I think I had < before in the if statement below, but the compareTo method compares the first to the second.
If i1 = 5 and i2 = 6, the < sign would switch them, which is what we don't want to do in this case. We want an augmenting list, so we should only swap them if the first is bigger than the second. Therefore, we want the > sign in the if statement instead (just a technical error on my part).
The actual code went something like this. Also, the code was really, really slow, probably because String temp = myArray[j-1]; kept creating a new temp during each pass and that just made the process a whole lot longer. There were probably other things too that made it incredibly slow, but I optimized it by just creating String temp and then temp would just be reassigned in the case that the if statement was true.
In the end, it was actually interesting to see how much slower my code was compared to the Collections sort in java, but it was also kinda sad and funny at the same time. :)
private static void bubblesort(String[] myArray)
{
String temp;
//before: not here^
for(int i=0; i<myArray.length; i++)
{
for(int j=1; j<myArray.length; j++)
{
if(myArray[j-1].compareTo(myArray[j])>0)
{
temp = myArray[j-1];
//before: String temp = myArray[j-1];
myArray[j-1] = myArray[j];
myArray[j] = temp;
}
}
}
}
{
String temp;
//before: not here^
for(int i=0; i<myArray.length; i++)
{
for(int j=1; j<myArray.length; j++)
{
if(myArray[j-1].compareTo(myArray[j])>0)
{
temp = myArray[j-1];
//before: String temp = myArray[j-1];
myArray[j-1] = myArray[j];
myArray[j] = temp;
}
}
}
}
No comments:
Post a Comment