Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Insertion sort
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Best, worst, and average cases== The best case input is an array that is already sorted. In this case insertion sort has a linear running time (i.e., O(''n'')). During each iteration, the first remaining element of the input is only compared with the right-most element of the sorted subsection of the array. The simplest worst case input is an array sorted in reverse order. The set of all worst case inputs consists of all arrays where each element is the smallest or second-smallest of the elements before it. In these cases every iteration of the inner loop will scan and shift the entire sorted subsection of the array before inserting the next element. This gives insertion sort a quadratic running time (i.e., O(''n''<sup>2</sup>)). The average case is also quadratic,<ref>{{cite web |last=Schwarz |first=Keith |title=Why is insertion sort Ξ(n^2) in the average case? (answer by "templatetypedef") |publisher=Stack Overflow |url=https://stackoverflow.com/a/17055342}}</ref> which makes insertion sort impractical for sorting large arrays. However, insertion sort is one of the fastest algorithms for sorting very small arrays, even faster than [[quicksort]]; indeed, good [[quicksort]] implementations use insertion sort for arrays smaller than a certain threshold, also when arising as subproblems; the exact threshold must be determined experimentally and depends on the machine, but is commonly around ten. Example: The following table shows the steps for sorting the sequence {3, 7, 4, 9, 5, 2, 6, 1}. In each step, the key under consideration is underlined. The key that was moved (or left in place because it was the biggest yet considered) in the previous step is marked with an asterisk. <u>3</u> 7 4 9 5 2 6 1 3* <u>7</u> 4 9 5 2 6 1 3 7* <u>4</u> 9 5 2 6 1 3 4* 7 <u>9</u> 5 2 6 1 3 4 7 9* <u>5</u> 2 6 1 3 4 5* 7 9 <u>2</u> 6 1 2* 3 4 5 7 9 <u>6</u> 1 2 3 4 5 6* 7 9 <u>1</u> 1* 2 3 4 5 6 7 9
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)