GeeksforGeeks » Interview Questions

tcs interview question

(2 posts)

Tags:

  1. prince
    guest
    Posted 9 months ago #

    how bubble sort has an order of complexity of o(n) in best case give the analysis?

  2. kartik
    Moderator
    Posted 9 months ago #

    Bubble sort takes O(n) time for already sorted array. Consider the following Bubble Sort algo from Wikipedia. If array is sorted then the do while loop is executed only once as the swap variable remains false after first iteration.

    procedure bubbleSort( A : list of sortable items )
      do
        swapped = false
        for each i in 1 to length(A) - 1 inclusive do:
          if A[i-1] > A[i] then
            swap( A[i-1], A[i] )
            swapped = true
          end if
        end for
      while swapped
    end procedure

Reply

You must log in to post.

RSS feed for this topic