长水痘可以吃什么菜| 胃粘膜损伤吃什么药| 界代表什么生肖| 白喉是什么病| 敕令是什么意思| 增肌吃什么| 梦见老公穿新衣服是什么意思| 什么的公园| 日语莫西莫西什么意思| 做梦梦见考试是什么意思| ufc是什么意思| 癌变是什么意思| 老人大小便失禁是什么原因造成的| 鹅肉不能和什么一起吃| 眼睛红是什么原因引起的| 床上放什么可以驱蟑螂| 社保卡属于什么银行| 暗是什么意思| 脚掌疼是什么原因| 脸无缘无故的肿是什么原因| 雪芽是什么| 23岁属什么生肖| 生意兴隆是什么意思| 什么的玻璃| 什么叫伴手礼| 琛字五行属什么| 1969年什么时候退休| 梦到跟人吵架是什么意思| 尿里带血是什么原因女性| 三叉神经吃什么药好| 随餐服用什么意思| 很能睡觉是什么原因| 氮是什么| 犬和狗有什么区别| 燃面为什么叫燃面| 财政部部长什么级别| 曦是什么意思| 衣冠禽兽是什么意思| 蓟类植物是什么| 苹果吃了有什么好处| 水洗棉是什么面料| 同房痛什么原因引起的| 大山羊是什么病| 浪琴军旗什么档次| 东窗事发是什么意思| 小龙虾什么季节吃最好| 怕冷畏寒是什么原因| 11月21日什么星座| 627是什么星座| 爱的本质是什么| 恒顺众生是什么意思| 坐月子什么不能吃| 粉领是什么意思| 黑色皮肤适合什么颜色的衣服| 芦荟有什么功效| 咳嗽吃什么药| 湿疹吃什么食物好得快| 针灸后需要注意什么| 吃灵芝有什么好处| 梦见掉牙齿是什么征兆| 四曾念什么| 射手属于什么象星座| 维生素B1有什么副作用| 天秤座是什么星象| 相对湿度是什么意思| 户籍信息是什么| 庚字五行属什么| 什么水果可以降火| 想一出是一出什么意思| 气血亏虚什么症状| ngu是什么意思| 什么是血友病| 甲状腺吃什么盐好| 什么叫肛裂| 嘴角烂了涂什么药| xxoo什么意思| 背疽是什么病| 样本是什么意思| 眼睛发蓝是什么原因| 靖康耻指的是什么历史事件| 产褥期是什么意思| 胃胀挂什么科| 陌上花是什么意思| hrd是什么意思| 碳酸氢铵是什么| 西京医院什么科室最强| 第一次为什么进不去| 什么是211大学| 嘴唇上长痣代表什么| 梦见晒被子是什么意思| 内什么外什么成语| 草莓是什么季节的水果| 疖肿是什么原因引起的| rolls是什么意思| 拉肚子呕吐吃什么药| 宫颈筛查是检查什么| 人体缺钾会有什么症状| 菊花像什么比喻句| 甲状腺什么症状| 左眼皮跳是什么预兆| 赫依病是什么病| 男的结扎有什么影响| 大林木命适合做什么行业| 手冲是什么| 抗磷脂综合征是什么病| 9月份有什么节日| 静电对人体有什么危害| 一吃就吐是什么病症| 发际线是什么| 女命正印代表什么| 氢化植物油是什么| 风疟病是什么意思| 7.2号是什么星座| 血小板减少有什么症状| 普罗帕酮又叫什么| 荨麻疹要注意些什么| 梦见搬家是什么意思| 牙龈发炎吃什么消炎药| ao是什么| 腰果有什么好处| 毛肚是什么动物身上的| 肝弥漫性病变是什么意思| 碎花裙配什么鞋子| birkin是什么意思| 大爱什么意思| 躯体化什么意思| 心态好是什么意思| 固精是什么意思| 双鱼座女和什么星座最配| 竹节棉是什么面料| 排场是什么意思| 甲钴胺有什么副作用| 久卧伤什么| 囡囡是什么意思| 赭是什么颜色| 为什么会突然头晕| 烤肉筋的肉是什么肉| 冬瓜有什么功效| 沙眼衣原体是什么病| wendy什么意思| 尿隐血是什么意思| 油炸食品用什么油最好| 道德绑架什么意思| 鳀鱼是什么鱼| 白带是什么意思| 赛脸什么意思| dm是什么意思| 尿素测定是查什么| 为什么不能抖腿| 胆囊壁毛糙吃什么药| 什么军官可以随身配枪| 女性漏尿吃什么药最好| 萎缩性胃炎吃什么药好| 心脏早搏有什么症状| 银五行属性是什么| 什么是匝道| 新疆是什么民族| 得了甲亢都有什么症状| 海参多少头是什么意思| 口干嗓子干是什么原因| 听调不听宣什么意思| 1975年是什么年| 梦见孩子哭是什么意思| 什么是厌氧菌感染| 口腔溃疡缺什么维生素| 焦虑症吃什么中成药| 维生素e有什么作用| 96100是什么电话| 凉拌菜用什么醋最好| 身体上有小红点是什么病| 贵人多忘事什么意思| 爱生气的人容易得什么病| 治鸡眼用什么药最好| 什么是溶血症| 中国的四大发明是什么| 哈密瓜为什么叫哈密瓜| 霉菌感染用什么药好| 符号代表什么| 什么之心路人皆知| 头晃动是什么病的前兆| 屈髋是什么姿势| 蔗糖素是什么| 夏天有什么花开| 玉的五行属性是什么| 属兔五行属什么| 看嘴唇挂什么科| 女性私处长什么样| 工科和理科有什么区别| 干姜和生姜有什么区别| 燕窝有什么营养价值| 右胳膊上长痣代表什么| 指标什么意思| 老枞水仙属于什么茶| 抗风疹病毒抗体igg高是什么意思| 手镯断了有什么预兆| 参合是什么意思| 鲁班姓什么| 梅核气是什么病| 螃蟹和什么食物相克| 什么花可以吃| 什么叫贵妃镯| 胆怯是什么意思| 人体缺钾会有什么症状| 心肌酶高有什么危害| 大电念什么| 十月份出生的是什么星座| 什么是潜规则| 牛奶什么时间喝最佳| 汗为什么是咸的| 10月15号是什么星座| 缘是什么生肖| 双歧杆菌三联和四联有什么区别| 免签国家是什么意思| 手电筒的金属外壳相当于电路中的什么| 话唠是什么意思| 被迫是什么意思| 孕妇用什么驱蚊最安全| 高中学考是什么意思| 耳膜穿孔有什么症状| 黑舌头的狗是什么狗| 螳螂吃什么| 7月7日什么星座| 夹不住尿是什么原因| 什么叫腰肌劳损| 扁平疣是什么病| 什么都不怕| 为什么会长痘痘| 嗓子有痰是什么原因| 早射吃什么药最好| 什么中药补肾最好| 牛百叶是什么| 湿气重吃什么| hmb是什么意思| 为什么每次同房后都会尿路感染| 胰腺炎用什么药| 真菌感染是什么| green是什么颜色| 叶黄素什么时间吃最好| 医院手环颜色代表什么| 什么是欲望| 梦见自己大笑是什么意思| 世界上最毒的蛇是什么蛇| 1996年五行属什么| 骨皮质断裂是什么意思| 脚突然抽筋是什么原因| 胆囊结石用什么药好| 尿比重偏高是什么原因| 洁面液是干什么用的| 香蕉与什么食物相克| 办理住院手续需要带什么证件| 砂仁后下是什么意思| 什么品牌的假发好| 梦见前夫是什么兆头| 5月26是什么星座| 男人忽冷忽热说明什么| 血脂稠喝什么茶效果好| 嗯是什么意思| 属鼠和什么属相相冲| 火腿是什么动物的腿| 头晕头疼是什么原因| 看日历是什么生肖| 癌胚抗原是什么| 痹症是什么病| p是什么单位| 百度Jump to content

湖北省特级教师巡回讲学活动走进鹤峰 200名骨干教师享教学大餐

From Wikipedia, the free encyclopedia
(Redirected from Insertion Sort)
Insertion sort
Insertion sort animation
ClassSorting algorithm
Data structureArray
Worst-case performance comparisons and swaps
Best-case performance comparisons, swaps
Average performance comparisons and swaps
Worst-case space complexity total, auxiliary
OptimalNo
百度 他,独自一人把清华大学的冷原子凝聚态的科研水平提高了几十年。

Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time by comparisons. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort. However, insertion sort provides several advantages:

  • Simple implementation: Jon Bentley shows a version that is three lines in C-like pseudo-code, and five lines when optimized.[1]
  • Efficient for (quite) small data sets, much like other quadratic (i.e., O(n2)) sorting algorithms
  • More efficient in practice than most other simple quadratic algorithms such as selection sort or bubble sort
  • Adaptive, i.e., efficient for data sets that are already substantially sorted: the time complexity is O(kn) when each element in the input is no more than k places away from its sorted position
  • Stable; i.e., does not change the relative order of elements with equal keys
  • In-place; i.e., only requires a constant amount O(1) of additional memory space
  • Online; i.e., can sort a list as it receives it

When people manually sort cards in a bridge hand, most use a method that is similar to insertion sort.[2]

Algorithm

[edit]
A graphical example of insertion sort. The partial sorted list (black) initially contains only the first element in the list. With each iteration one element (red) is removed from the "not yet checked for order" input data and inserted in-place into the sorted list.

Insertion sort iterates, consuming one input element each repetition, and grows a sorted output list. At each iteration, insertion sort removes one element from the input data, finds the correct location within the sorted list, and inserts it there. It repeats until no input elements remain.

Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position.

The resulting array after k iterations has the property where the first k + 1 entries are sorted ("+1" because the first entry is skipped). In each iteration the first remaining entry of the input is removed, and inserted into the result at the correct position, thus extending the result:

Array prior to the insertion of x

becomes

Array after the insertion of x

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:

  1. Suppose there exists a function called Insert designed to insert a value into a sorted sequence at the beginning of an array. It operates by beginning at the end of the sequence and shifting each element one place to the right until a suitable position is found for the new element. The function has the side effect of overwriting the value stored immediately after the sorted sequence in the array.
  2. To perform an insertion sort, begin at the left-most element of the array and invoke Insert to insert each element encountered into its correct position. The ordered sequence into which the element is inserted is stored at the beginning of the array in the set of indices already examined. Each insertion overwrites a single value: the value being inserted.

Pseudocode of the complete algorithm follows, where the arrays are zero-based:[1]

i ← 1
while i < length(A)
    j ← i
    while j > 0 and A[j-1] > A[j]
        swap A[j] and A[j-1]
        j ← j - 1
    end while
    i ← i + 1
end while

The outer loop runs over all the elements except the first one, because the single-element prefix A[0:1] is trivially sorted, so the invariant that the first i entries are sorted is true from the start. The inner loop moves element A[i] to its correct place so that after the loop, the first i+1 elements are sorted. Note that the and-operator in the test must use short-circuit evaluation, otherwise the test might result in an array bounds error, when j=0 and it tries to evaluate A[j-1] > A[j] (i.e. accessing A[-1] fails).

After expanding the swap operation in-place as x ← A[j]; A[j] ← A[j-1]; A[j-1] ← x (where x is a temporary variable), a slightly faster version can be produced that moves A[i] to its position in one go and only performs one assignment in the inner loop body:[1]

i ← 1
while i < length(A)
    x ← A[i]
    j ← i
    while j > 0 and A[j-1] > x
        A[j] ← A[j-1]
        j ← j - 1
    end while
    A[j] ← x[3]
    i ← i + 1
end while

The new inner loop shifts elements to the right to clear a spot for x = A[i].

The algorithm can also be implemented in a recursive way. The recursion just replaces the outer loop, calling itself and storing successively smaller values of n on the stack until n equals 0, where the function then returns up the call chain to execute the code after each recursive call starting with n equal to 1, with n increasing by 1 as each instance of the function returns to the prior instance. The initial call would be insertionSortR(A, length(A)-1).

function insertionSortR(array A, int n)
    if n > 0
        insertionSortR(A, n-1)
        x ← A[n]
        j ← n-1
        while j >= 0 and A[j] > x
            A[j+1] ← A[j]
            j ← j-1
        end while
        A[j+1] ← x
    end if
end function

It does not make the code any shorter, it also does not reduce the execution time, but it increases the additional memory consumption from O(1) to O(N) (at the deepest level of recursion the stack contains N references to the A array, each with accompanying value of variable n from N down to 1).

Best, worst, and average cases

[edit]

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(n2)).

The average case is also quadratic,[4] 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.

3  7  4  9  5  2  6  1
3* 7  4  9  5  2  6  1
3  7* 4  9  5  2  6  1
3  4* 7  9  5  2  6  1
3  4  7  9* 5  2  6  1
3  4  5* 7  9  2  6  1
2* 3  4  5  7  9  6  1
2  3  4  5  6* 7  9  1
1* 2  3  4  5  6  7  9

Relation to other sorting algorithms

[edit]

Insertion sort is very similar to selection sort. As in selection sort, after k passes through the array, the first k elements are in sorted order. However, the fundamental difference between the two algorithms is that insertion sort scans backwards from the current key, while selection sort scans forwards. This results in selection sort making the first k elements the k smallest elements of the unsorted input, while in insertion sort they are simply the first k elements of the input.

The primary advantage of insertion sort over selection sort is that selection sort must always scan all remaining elements to find the absolute smallest element in the unsorted portion of the list, while insertion sort requires only a single comparison when the (k + 1)-st element is greater than the k-th element; when this is frequently true (such as if the input array is already sorted or partly sorted), insertion sort is distinctly more efficient compared to selection sort. On average (assuming the rank of the (k + 1)-st element rank is random), insertion sort will require comparing and shifting half of the previous k elements, meaning that insertion sort will perform about half as many comparisons as selection sort on average.

In the worst case for insertion sort (when the input array is reverse-sorted), insertion sort performs just as many comparisons as selection sort. However, a disadvantage of insertion sort over selection sort is that it requires more writes due to the fact that, on each iteration, inserting the (k + 1)-st element into the sorted portion of the array requires many element swaps to shift all of the following elements, while only a single swap is required for each iteration of selection sort. In general, insertion sort will write to the array O(n2) times, whereas selection sort will write only O(n) times. For this reason selection sort may be preferable in cases where writing to memory is significantly more expensive than reading, such as with EEPROM or flash memory.

While some divide-and-conquer algorithms such as quicksort and mergesort outperform insertion sort for larger arrays, non-recursive sorting algorithms such as insertion sort or selection sort are generally faster for very small arrays (the exact size varies by environment and implementation, but is typically between 7 and 50 elements). Therefore, a useful optimization in the implementation of those algorithms is a hybrid approach, using the simpler algorithm when the array has been divided to a small size.[1]

Variants

[edit]

D.L. Shell made substantial improvements to the algorithm; the modified version is called Shell sort. The sorting algorithm compares elements separated by a distance that decreases on each pass. Shell sort has distinctly improved running times in practical work, with two simple variants requiring O(n3/2) and O(n4/3) running time.[5][6]

If the cost of comparisons exceeds the cost of swaps, as is the case for example with string keys stored by reference or with human interaction (such as choosing one of a pair displayed side-by-side), then using binary insertion sort may yield better performance.[7] Binary insertion sort employs a binary search to determine the correct location to insert new elements, and therefore performs ?log2 n? comparisons in the worst case. When each element in the array is searched for and inserted this is O(n log n).[7] The algorithm as a whole still has a running time of O(n2) on average because of the series of swaps required for each insertion.[7]

The number of swaps can be reduced by calculating the position of multiple elements before moving them. For example, if the target position of two elements is calculated before they are moved into the proper position, the number of swaps can be reduced by about 25% for random data. In the extreme case, this variant works similar to merge sort.

A variant named binary merge sort uses a binary insertion sort to sort groups of 32 elements, followed by a final sort using merge sort. It combines the speed of insertion sort on small data sets with the speed of merge sort on large data sets.[8]

To avoid having to make a series of swaps for each insertion, the input could be stored in a linked list, which allows elements to be spliced into or out of the list in constant time when the position in the list is known. However, searching a linked list requires sequentially following the links from each element to the next (or previous) element: a linked list does not have random access, so it cannot use a faster method such as binary search to find the insertion point for an unsorted element. Therefore, the running time required for searching is O(n), and the time for sorting is O(n2). If a more sophisticated data structure (e.g., heap or binary tree) is used, the time required for searching and insertion can be reduced significantly; this is the essence of heap sort and binary tree sort.

In 2006 Bender, Martin Farach-Colton, and Mosteiro published a new variant of insertion sort called library sort or gapped insertion sort that leaves a small number of unused spaces (i.e., "gaps") spread throughout the array. The benefit is that insertions need only shift elements over until a gap is reached. The authors show that this sorting algorithm runs with high probability in O(n log n) time.[9]

If a skip list is used, the insertion time is brought down to O(log n), and swaps are not needed because the skip list is implemented on a linked list structure. The final running time for insertion would be O(n log n).

List insertion sort code in C

[edit]

If the items are stored in a linked list, then the list can be sorted with O(1) additional space. The algorithm starts with an initially empty (and therefore trivially sorted) list. The input items are taken off the list one at a time, and then inserted in the proper place in the sorted list. When the input list is empty, the sorted list has the desired result.

struct LIST * SortList1(struct LIST * pList) 
{
    // zero or one element in list
    if (pList == NULL || pList->pNext == NULL)
        return pList;
    // head is the first element of resulting sorted list
    struct LIST * head = NULL;
    while (pList != NULL) {
        struct LIST * current = pList;
        pList = pList->pNext;
        if (head == NULL || current->iValue < head->iValue) {
            // insert into the head of the sorted list
            // or as the first element into an empty sorted list
            current->pNext = head;
            head = current;
        } else {
            // insert current element into proper position in non-empty sorted list
            struct LIST * p = head;
            while (p != NULL) {
                if (p->pNext == NULL || // last element of the sorted list
                    current->iValue < p->pNext->iValue) // middle of the list
                {
                    // insert into middle of the sorted list or as the last element
                    current->pNext = p->pNext;
                    p->pNext = current;
                    break; // done
                }
                p = p->pNext;
            }
        }
    }
    return head;
}

The algorithm below uses a trailing pointer[10] for the insertion into the sorted list. A simpler recursive method rebuilds the list each time (rather than splicing) and can use O(n) stack space.

struct LIST
{
  struct LIST * pNext;
  int           iValue;
};

struct LIST * SortList(struct LIST * pList)
{
  // zero or one element in list
  if (!pList || !pList->pNext)
      return pList;

  /* build up the sorted array from the empty list */
  struct LIST * pSorted = NULL;

  /* take items off the input list one by one until empty */
  while (pList != NULL) {
      /* remember the head */
      struct LIST *   pHead  = pList;
      /* trailing pointer for efficient splice */
      struct LIST ** ppTrail = &pSorted;

      /* pop head off list */
      pList = pList->pNext;

      /* splice head into sorted list at proper place */
      while (!(*ppTrail == NULL || pHead->iValue < (*ppTrail)->iValue)) { /* does head belong here? */
          /* no - continue down the list */
          ppTrail = &(*ppTrail)->pNext;
      }

      pHead->pNext = *ppTrail;
      *ppTrail = pHead;
  }

  return pSorted;
}

References

[edit]
  1. ^ a b c d Bentley, Jon (2000). "Column 11: Sorting". Programming Pearls (2nd ed.). ACM Press / Addison-Wesley. pp. 115–116. ISBN 978-0-201-65788-3. OCLC 1047840657.
  2. ^ Sedgewick, Robert (1983). Algorithms. Addison-Wesley. p. 95. ISBN 978-0-201-06672-2.
  3. ^ Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2009) [1990], "Section 2.1: Insertion sort", Introduction to Algorithms (3rd ed.), MIT Press and McGraw-Hill, pp. 16–18, ISBN 0-262-03384-4. See page 18.
  4. ^ Schwarz, Keith. "Why is insertion sort Θ(n^2) in the average case? (answer by "templatetypedef")". Stack Overflow.
  5. ^ Frank, R. M.; Lazarus, R. B. (1960). "A High-Speed Sorting Procedure". Communications of the ACM. 3 (1): 20–22. doi:10.1145/366947.366957. S2CID 34066017.
  6. ^ Sedgewick, Robert (1986). "A New Upper Bound for Shellsort". Journal of Algorithms. 7 (2): 159–173. doi:10.1016/0196-6774(86)90001-5.
  7. ^ a b c Samanta, Debasis (2008). Classic Data Structures. PHI Learning. p. 549. ISBN 9788120337312.
  8. ^ "Binary Merge Sort"
  9. ^ Bender, Michael A.; Farach-Colton, Martín; Mosteiro, Miguel A. (2006). "Insertion sort is O(n log n)". Theory of Computing Systems. 39 (3): 391–397. arXiv:cs/0407003. doi:10.1007/s00224-005-1237-z. MR 2218409. S2CID 14701669.
  10. ^ Hill, Curt (ed.), "Trailing Pointer Technique", Euler, Valley City State University, archived from the original on 26 April 2012, retrieved 22 September 2012.

Further reading

[edit]
[edit]
脑梗什么不能吃 小腿发麻是什么原因 三高挂号挂什么科 风湿属于什么科 胃酸过多是什么原因造成的
孕期便秘吃什么通便快 米豆腐是什么做的 农历5月20日是什么星座 鼻甲肥大是什么原因 为什么会有同性恋
类风湿要吃什么药 脊髓是什么 pca是什么意思 眼睛屈光不正是什么 皮肤晒伤用什么药
女人阴道痒是什么原因 吃什么药可以推迟月经 小孩反复发烧是什么原因 四季平安是什么生肖 相思什么意思
内能与什么有关hcv8jop9ns3r.cn 乳夹是什么hcv8jop2ns0r.cn 甲沟炎是什么样子的hcv9jop2ns5r.cn 手部湿疹用什么药膏hcv8jop5ns1r.cn 惜败是什么意思hcv8jop2ns2r.cn
五灵脂是什么东西cl108k.com 湿气重怎么调理吃什么hcv8jop9ns3r.cn 瞒天过海是什么意思520myf.com 金代表什么生肖hcv8jop7ns3r.cn 腐竹炒什么好吃hcv9jop2ns8r.cn
叫床是什么意思0297y7.com 1什么意思hcv8jop6ns3r.cn 五月二十一号是什么星座hcv9jop5ns7r.cn 属龙五行属什么hcv8jop7ns8r.cn 月经期喝什么茶好hcv9jop3ns3r.cn
炸东西用什么淀粉hcv9jop5ns5r.cn 左侧卵巢无回声是什么意思hcv8jop2ns9r.cn 柯字五行属什么hcv9jop1ns6r.cn mini是什么车wmyky.com 县委办公室主任是什么级别hcv8jop8ns9r.cn
百度