I got a question that which type of sorting algorithm will have least time complexity when we are given an already sorted array.
3 Answers 3
Wikipedia has a table showing a comparison of the best, average and worst-case performance of many different sorting algorithms. Here's an excerpt:
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.
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).
-
2Read 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.pjs– pjs2017年07月12日 23:00:12 +00:00Commented 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.Greenstick– Greenstick2017年07月13日 19:25:37 +00:00Commented Jul 13, 2017 at 19:25
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
-
3
-
answer seems to be truncated; please complete or correctLuca Basso Ricci– Luca Basso Ricci2025年03月13日 06:37:47 +00:00Commented Mar 13 at 6:37
if(isSorted(list)) return; anySortAlgorithmYouLike(list);