| Tutorial ID | 101 |
|---|---|
| Title | Insertion sort |
Algorithm Every repetition of insertion sort removes an element from the input data, inserting it into the correct position in the already-sorted list, until no input elements remain. The choice of which element to remove from the input is arbitrary, and can be made using almost any choice algorithm. Sorting is typically done in-place. The resulting array after k iterations has the property where the first k + 1 entries are sorted. In each iteration the first remaining entry of the input is removed, inserted into the result at the correct position, thus extending the result:
becomes
with each element greater than x copied to the right as it is compared against x. The most common variant of insertion sort, which operates on arrays, can be described as follows:
Pseudocode of the complete algorithm follows, where the arrays are zero-based:
for i ← 1 to i ← length(A)-1 { // A[ i ] is added in the sorted sequence A[0, .. i-1] // save A[i] to make a hole at index iHole item ← A[i] iHole ← i // keep moving the hole to next smaller index until A[iHole - 1] is <= item while iHole > 0 and A[iHole - 1] > item { // move hole to next smaller index A[iHole] ← A[iHole - 1] iHole ← iHole - 1 } // put item in the hole A[iHole] ← item } Reference: Wikipedia | |
| problem_id | title | description | submit | accepted | difficulty |
|---|---|---|---|---|---|
| 1084 | Sorting I | Sorting is a basic problem in Computer Science. Can you write a program to sort integers? | 12 | 9 | 0 |
Facebook