I was trying out bubble sort. I want to figure out how to determine the Big(o) of a particular algorithm.
public class BubbleSort {
public int[] bubblesort(int[] numbers){
int temp;
for(int i =0; i< numbers.length; i++){
for(int j = 1; j< numbers.length-i; j++){
if(numbers[j-1] > numbers[j]){
temp = numbers[j-1];
numbers[j-1] = numbers[j];
numbers[j] = temp;
}
}
}
return numbers;
}
public static void main(String args[]){
int[] n = new int[]{4,3,2,1};
long startTime = System.nanoTime();
System.out.println(Arrays.toString(new BubbleSort().bubblesort(n)));
long endTime = System.nanoTime();
System.out.println("bubblesort : " + (endTime - startTime));
}
}
The optimized bubble sort does this:
compare & swap 4,3; compare & swap 4, 2; compare & swap 4, 1; start again
compare & swap 3, 2; compare & swap 3, 1; start again
compare & swap 2, 1; done
From Wiki i see that worst case analysis is O(n^2)
. how they came to a conclusion that the worst case analysis of this algorithm is O(n^2)
. I want to see this programmatically on how they are coming to worst case analysis of a giving algorithm.
The algorithm does EXACTLY (n^2) operations
from what i understand, is there a way to programmatically get the result?