3

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

asked Jul 12, 2017 at 19:07
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 O(n) running times for best-case inputs (i.e., pre-sorted data). However, most of them (like bubble sort, for example) have O(n2) 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 O(n log n) average and worst-case running times. These are as follows:

I would recommend using one of these.

answered Jul 12, 2017 at 22:01
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).

answered Jul 12, 2017 at 19:11
2
  • 2
    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. Commented Jul 12, 2017 at 23:00
  • 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. Commented Jul 13, 2017 at 19:25
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

answered Mar 12 at 12:48
2
  • 3
    The suspense ... Commented Mar 12 at 15:22
  • answer seems to be truncated; please complete or correct Commented Mar 13 at 6:37

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.