由于插入排序的基本思想是在一个有序序列中插入一个新的记录,则可以利用"折半查找"查询插入位置,由此得到的插入排序算法为"折半插入排序"。算法如下:
<pre name="code" class="cpp"><span style="font-size:18px;">void BInsertSort () { // 对顺序表L作折半插入排序 for ( i=2; i<=length; ++i ) { r[0] = r[i]; // 将L.r[i]暂存到L.r[0] low = 1; high = i-1; while (low<=high) { // 在r[low..high]中折半查找有序插入的位置 m = (low+high)/2; // 折半 if (r[0] < r[m])</span><span style="font-size:18px;"><span style="white-space:pre"></span> high = m-1; // 插入点在低半区 else </span><span style="font-size:18px;"> <span style="white-space:pre"></span> low = m+1; // 插入点在高半区 <span style="white-space:pre"></span> } // while <span style="white-space:pre"></span> for ( j=i-1; j>=low; –j ) </span><span style="font-size:18px;"><span style="white-space:pre"></span>r[j+1] = r[j]; // 记录后移 r[high+1] = r[0]; // 插入 }} // BInsertSort</span>
但是,折半插入排序只能减少排序过程中关键字比较的时间,并不能减少记录移动的时间,因此折半插入排序的时间复杂度仍为O (n2)。
版权声明:本文为博主原创文章,,未经博主允许不得转载。
你不怕困难,困难就怕你。