M9A
M9A

Reputation: 3286

Count number of comparisons of a sorting algorithm and add it to an array list in java

Hi I have a generic bubble sort algorithm which I am using and I want to track the number of comparisons that occur before the array is sorted. The number of comparisons must be stored in an array list. I am not too sure how to do this so I was wondering if anyone can help. Thanks

protected static ArrayList<Integer> noOfComparisons = new ArrayList<Integer>();

public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) {
boolean changed = false;
do {
    changed = false;
    for (int a = 0; a < comparable.length - 1; a++) {
        if (comparable[a].compareTo(comparable[a + 1]) > 0) {
            E tmp = comparable[a];
            comparable[a] = comparable[a + 1];
            comparable[a + 1] = tmp;
            changed = true;
        }
    }
} while (changed);
}

Upvotes: 0

Views: 1697

Answers (1)

driangle
driangle

Reputation: 11779

You will need to keep track of the number of comparisons every time you sort an array. To do so, create an int initialized at zero at the beginning of the bubbleSort method, and then increase that number whenever a comparison is performed. At the end of your bubbleSort method, add that int to the list.

Upvotes: 2

Related Questions