请输入您要查询的字词:

 

单词 InsertionSort
释义

insertion sort


The Problem

See the sorting problem.

The Algorithm

Suppose L={x1,x2,,xn} is the initial list of unsorted elements.The insertion sort algorithmMathworldPlanetmath will construct a new list, containing theelements of L in order, which we will call L. The algorithm constructs this list one element at a time.

Initially L is empty. We then take the first element of L and put it in L.We then take the second element of L and also add it to L, placing it before any elements in L that shouldcome after it. This is done one element at a time until all n elements of L are in L, in sorted order.Thus, each step i consists of looking up the position in L where the element xi should be placedand inserting it there (hence the name of the algorithm).This requires a search, and then the shifting of all the elements in Lthat come after xi (if L is stored in an array). If storage is in an array, then the binary search algorithmcan be used to quickly find xi’s new position in L.

Since at step i, the length of list L is i and the length of list L is n-i, we can implement thisalgorithm as an in-place sorting algorithm. Each step i results in L[1..i] becoming fully sorted.

Pseudocode

This algorithm uses a modified binary search algorithm to find the position in L where an element keyshould be placed to maintain orderingMathworldPlanetmath.

Algorithm Insertion_Sort(L, n)
Input: A list L of n elements
Output: The list L in sorted order

begin
         for i1 to n do

begin

valueL[i]

positionBinary_Search(L,1,i,value)

for ji downto position do

L[j]L[j-1]

L[position]value

end
end

function Binary_Search(L, bottom, top, key)
begin
         if bottomtop then

Binary_Searchbottom

else

begin

middle(bottom+top)/2

if key<L[middle] then

Binary_SearchBinary_Search(L,bottom,middle-1,key)

else

Binary_SearchBinary_Search(L,middle+1,top,key)

end
end

Analysis

In the worst case, each step i requires a shift of i-1 elements for the insertion (consider an inputlist that is sorted in reverse order). Thus the runtime complexity is 𝒪(n2). Even the optimizationof using a binary searchMathworldPlanetmath does not help us here, because the deciding factor in this case is the insertion.It is possible to use a data type with 𝒪(logn) insertion time, giving 𝒪(nlogn) runtime,but then the algorithm can no longer be done as an in-place sorting algorithm. Such data structures are also quitecomplicated.

A similar algorithm to the insertion sort is the selection sortMathworldPlanetmath, which requires fewer data movements than the insertionsort, but requires more comparisons.

随便看

 

数学辞典收录了18232条数学词条,基本涵盖了常用数学知识及数学英语单词词组的翻译及用法,是数学学习的有利工具。

 

Copyright © 2000-2023 Newdu.com.com All Rights Reserved
更新时间:2025/5/4 11:05:14