The best case for sorting bubbles

I want to know what would be the best option for creating bubbles? There may be times when, for example, there can be no substitute for the last two passes. I am doing my C program. Suppose I have an array of 5 elements and I give the elements as 1 2 5 4 3, then there would be no changes in the last 2 passes?

+5
source share
9 answers

The best scenario is one run. The list will already be sorted. Without swap = done.

+25
source

: , . ) , , O (n2) ) , . . (n-1) , , O (n).

+20

. :

(n²), n - . O (n log n). (n²), , . , n .

  • O (n²)
  • O (n)
  • O (n²)
  • O (n) total, O (1)
+9

, . - - - , , .

+2

, , . , , . O (n ^ 2).

BUBBLESORT(A)
1 for i = 1 to A.length - 1
2     for j = A.length downto i + 1
3         if A[j] < A[j - 1]
4             exchange A[j] with A[j - 1]

, (), , , , , O (n) O (n ^ 2)

    procedure bubbleSort( A : list of sortable items )
    n = length(A)
    repeat 
        swapped = false
        for i = 1 to n-1 inclusive do
            /* if this pair is out of order */
            if A[i-1] > A[i] then
                /* swap them and remember something changed */
                swap( A[i-1], A[i] )
                swapped = true
            end if
        end for
    until not swapped
end procedure

, C: https://youtu.be/qOpNrqqTsk4

+2

, .

, .

+1

, , - O (n2),

BUBBLESORT(A)
1 for i = 1 to A.length - 1
2     for j = A.length downto i + 1
3         if A[j] < A[j - 1]
4             exchange A[j] with A[j - 1]

it is so important whether the array is sorted or not, there are no passes becoz, even if line 4 is skipped, lines 2 and 3 are executed propositionally up to n2 times

edit: I think I got it, but still I need to modify the algorithm by adding let say boolean variable is_exchange, setting it to false before entering the second cycle, and if it returns again after exiting the cycle, we will end, and in in this case, the time will be O (n) becoz the second cycle is executed n times

0
source

All Articles