Search code examples
javabubble-sort

My check algorithm doesn't stop bubble sort


I have one file with 25 values of magnitude. I've checked that my bubble sort algorithm managed for 19 or 20 loops. My check method doesn't stop algorithm, It writes 24 loop needed. I can't understand, what I do wrong. It is zip file, where you can find data folder and nov20quakedatasmall.atom fid to test

import java.util.*;
import edu.duke.*;

public class QuakeSortInPlace {

public boolean checkInSortedOrder (ArrayList<QuakeEntry> quakes) {
    boolean stat = true;
    for (int i = 0; i< quakes.size()-1; i++) {
        double fParametr = quakes.get(i).getMagnitude();
        double sParametr = quakes.get(i+1).getMagnitude();
        if (fParametr < sParametr) {
            stat = true;
        }
        else {
            stat = false;
            break;
        }
    }
    return stat;
}

public void onePassBubbleSort (ArrayList <QuakeEntry> quakeData, int numSorted) {
    int loops = 0;
    //boolean isSorted = true;
   
        for (int i = 0; i<numSorted; i++) {
            //isSorted = true;
            for (int k = 0; k<quakeData.size()-i-1; k++) {
                double firstCompElement = quakeData.get(k).getMagnitude();
                double secondCompElement = quakeData.get(k+1).getMagnitude();
                if (firstCompElement > secondCompElement) {
                    QuakeEntry first = quakeData.get(k);
                    QuakeEntry second = quakeData.get(k+1);
                    quakeData.set(k+1 ,first);
                    quakeData.set(k,second);
                    // isSorted = false;
                }
                
            }
            loops++;
            
            if (checkInSortedOrder(quakeData)) {
                break;
            }
            // if (isSorted) {
               // break;
            // }          
    }
    System.out.print("We needed: "+loops);

}

public void sortByMagnitudeWithBubbleSortWithCheck (ArrayList<QuakeEntry> in) {
    int numOfElements = in.size();
    int finalNumOfElements = numOfElements-1;
    onePassBubbleSort (in, finalNumOfElements);
    
}

public void testSort() {
    EarthQuakeParser parser = new EarthQuakeParser(); 
    String source = "data/nov20quakedatasmall.atom";
    ArrayList<QuakeEntry> list  = parser.read(source); 
    System.out.println("read data for "+list.size()+" quakes");    
    sortByMagnitudeWithBubbleSortWithCheck(list);
    for (QuakeEntry qe: list) { 
         System.out.println(qe);
    } 
    
}

}


Solution

  • There are two entries in your source file that have the same value. This triggers the "else" in your if-statement and causes the program to continue with the next loop.

    if (fParametr < sParametr) {
                stat = true;
            }
            else {
                stat = false;
                break;
            } 
    

    Changing (fParametr < sParametr) to (fParametr <= sParametr) should fix the problem.