I have two Methods which have to be void methods, they are using a propriety from the elements in the list named Magnitude to sort them using bubble sort from the smallest to largest, the method OnePassBubbleSort orders one element at a time and sortByMagnitudeWithBubbleSort runs the sorting the times needed to get to get the answer the problem is that the quake with magnitude 2.6 does not seem to order properly.
my code is this:
public void onePassBubbleSort(ArrayList<QuakeEntry> quakes, int numSorted) {
int minIdx = 0;
for (int i=0 + 1; i< quakes.size()-numSorted; i++) {
if (quakes.get(i).getMagnitude() < quakes.get(minIdx).getMagnitude()) {
QuakeEntry qi = quakes.get(i);
QuakeEntry qmin = quakes.get(minIdx);
quakes.set(i,qmin);
quakes.set(minIdx,qi);
minIdx = i;
}
}
System.out.println("Printing Quakes after pass " + numSorted );
for(QuakeEntry qe: quakes){
System.out.println(qe.toString());
}
}
public void sortByMagnitudeWithBubbleSort(ArrayList<QuakeEntry> in) {
for (int i=0; i< in.size()-1; i++) {
onePassBubbleSort(in,i);
}
}
the original data is
and my result output is
my guess is that I have to return the list from the onepassbubblesort, and run that list again, but I that cannot be done with void methods
You sorting method is only moving the minIdx = i;
pointer when there is a match, causing it not to line up if the first element is smaller. Effectively, you are only swapping the first element and any other element you encountered when they match.
A fix for this would be moving the minIdx = i;
outside the if statement so it will always get called:
for (int i=0 + 1; i< quakes.size()-numSorted; i++) {
if (quakes.get(i).getMagnitude() < quakes.get(minIdx).getMagnitude()) {
QuakeEntry qi = quakes.get(i);
QuakeEntry qmin = quakes.get(minIdx);
quakes.set(i,qmin);
quakes.set(minIdx,qi);
}
minIdx = i;
}
Because the way you coded you function to accept a numSorted
argument, another solution to the problem would be assigment minIdx
to this variable:
minIdx = numSorted;