I tried to understand the data structure and another algorithm, then I got confused to measure the complexity of the Bubble sort time.
for (c = 0; c < ( n - 1 ); c++) { for (d = 0; d < n - c - 1; d++) { if (array[d] > array[d+1]) { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } }
Now every Big O talks about the best case O (n), the case Avg (n2) and the worst case (n2). But when I see the code found in the inner loop of the first phase, run n times, and then in the second phase n - 1, n - 2, etc. This means that at each iteration its value decreases. For example, if I have [] = {4, 2, 9, 5, 3, 6, 11}, then the total number of comparisons will be -
1st Phase - 7 time 2nd phase - 6 time 3rd Phase - 5 time 4th Phase - 4 time 5th Phase - 3 time 6th Phase - 2 time 7th Phase - 1 time
so when I calculate the time it looks like = (7 + 6 + 5 + 4 + 3 + 2 + 1) + 7 = 35, but the worst time complexity is n2 according to the document.
so can someone tell me how to calculate the correct value.
source share