3

I got a question that which type of sorting algorithm will have least time complexity when we are given an already sorted array.

1
  • 2
    if(isSorted(list)) return; anySortAlgorithmYouLike(list); Commented Jul 12, 2017 at 20:53

3 Answers 3

5

Wikipedia has a table showing a comparison of the best, average and worst-case performance of many different sorting algorithms. Here's an excerpt:

enter image description here

There are plenty of algorithms that have 𝓞(𝑛) running times for best-case inputs (i.e., pre-sorted data). However, most of them (like bubble sort, for example) have 𝓞(𝑛²) running times for average and worst-case inputs. This is something you really want to avoid. Sorting a million items with one of these algorithms will take an eternity.

Fortunately, a few of these algorithms have 𝓞(𝑛 log 𝑛) average and worst-case running times. These are as follows:

I would recommend using one of these.

Sign up to request clarification or add additional context in comments.

Comments

0

Sounds like a homework question, but I'd say one very simple algorithm that is time efficient on sorted or only slightly unsorted lists is bubble sort. Sorted, the time complexity is O(n). That said, there are many sorting algorithms that have similar time complexity for the best case scenario (i.e. already sorted), and bubble sort has a worst case of O(n2).

2 Comments

Read the Performance section of Wikipedia's bubble sort page to find out why insertion sort is probably a better choice. Insertion sort is also O(n) when the data are already sorted, and does better when the data are strongly ordered but not completely sorted.
All true, my recommendation of bubble sort is based on its ease of implementation and fulfillment of the basic criteria laid out by the question asker: that it is computationally efficient on a sorted array. In practice, there are many algorithms that are superior to bubble sort.
0

Its Insertion Sort. if you are taking a college level class they always use CLRS in the states and the answer is Insertion sort because you never enter the inner loop to do the swap if its already sorted. This results in 0 (n) because you

2 Comments

The suspense ...
answer seems to be truncated; please complete or correct

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.