插入排序 (Insert Sort)

Wiki : http://en.wikipedia.org/wiki/Insertion_sort


看看下面的动态图片, 就明白插入排序是怎么回事了:

WiKi上给出的伪代码:

Pseudocode of the complete algorithm follows, where the arrays arezero-based:

 // The values in A[i] are checked in-order, starting at the second one
 for i ← 1 to i ← length(A)-1
   {
     // at the start of the iteration, A[0..i-1] are in sorted order
     // this iteration will insert A[i] into that sorted order
 
     // save A[i], the value that will be inserted into the array on this iteration
     valueToInsert ← A[i]
     // now mark position i as the hole; A[i]=A[holePos] is now empty
     holePos ← i
     // keep moving the hole down until the valueToInsert is larger than 
     // what's just below the hole or the hole has reached the beginning of the array
     while holePos > 0 and valueToInsert < A[holePos - 1]
       { //value to insert doesn't belong where the hole currently is, so shift 
         A[holePos] ← A[holePos - 1] //shift the larger value up
         holePos ← holePos - 1       //move the hole position down
       }
     // hole is in the right position, so put valueToInsert into the hole
     A[holePos] ← valueToInsert
     // A[0..i] are now in sorted order
   }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
插入排序是一种简单且直观的排序算法。它的基本思想是将一个待排序的数组分成两个部分,一部分是已经排好序的,另一部分是未排序的。在每一次排序过程中,从未排序的部分中取出一个元素插入到已排序的部分中的适当位置,直到所有元素都被插入到已排序的部分中为止。 以下是一个使用微机汇编语言实现的插入排序算法: ```assembly ; 插入排序 ; 参数:edi - 待排序的数组首地址,ecx - 数组元素个数 InsertionSort: mov ebx, 1 ; ebx = 1,从第二个元素开始插入排序 OuterLoop: cmp ebx, ecx ; 检查是否已经排完序 jge Exit ; 如果已经排完序,跳转到 Exit mov eax, [edi + ebx * 4] ; 取出当前待排序的元素 mov edx, ebx ; 将 edx 指向当前待排序元素的前一个元素 InnerLoop: cmp edx, 0 ; 如果已经到了数组的起始位置,跳转到 Insert jl Insert mov esi, [edi + edx * 4] ; 取出当前已排序的元素 cmp esi, eax ; 比较当前已排序的元素和待排序的元素大小 jle Insert ; 如果当前已排序的元素小于等于待排序的元素,跳转到 Insert mov [edi + (edx + 1) * 4], esi ; 将当前已排序的元素后移一位 dec edx ; 将 edx 指向下一个已排序的元素 jmp InnerLoop Insert: mov [edi + (edx + 1) * 4], eax ; 将待排序的元素插入到已排序的部分中 inc ebx ; 将 ebx 指向下一个待排序的元素 jmp OuterLoop Exit: ret ``` 在该算法中,我们使用了寄存器 ebx,eax,edx 和 esi 来存储一些临时变量。其中,ebx 存储当前待排序的元素的下标,eax 存储当前待排序的元素的值,edx 存储当前待排序的元素前面一个已排序的元素的下标,esi 存储当前已排序的元素的值。 该算法的时间复杂度为 O(n^2),其中 n 是数组的元素个数。虽然该算法的效率不高,但是它非常容易实现,并且可以在实际应用中发挥一些作用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值