首页 > 代码库 > 二路插入排序

二路插入排序

#include<iostream>  
using namespace std;  
typedef int SqList[8];  
void Binpath_Insertsort(SqList &L,int count)  
{    
        int length = count - 1;  
    int L1[length] = { 0 };  
    L1[0] = L[1];//L中的第一个记录为L1中排好序的记录    
    int first = 0, last = 0;   
    for (int i = 2; i <= length; ++i)//依次将L的第2个至最后一个记录插入L1中    
    {  
        if (L[i] < L1[first])//待插入记录小于L1中最小值,插入到L1[first]之前   
        {  
            first = (first - 1 + length) % length;  
            L1[first] = L[i];  
        }  
        else if (L[i] > L1[last])//待插入记录大于L1中最小值,插入到L1[last]之后    
        {  
            last = last + 1;  
            L1[last] = L[i];  
        }  
        else  
        {  
            int j = last++;  
            while (L[i] <L1[j])  
            {  
                L1[(j + 1) % length] = L1[j];  
                j = (j - 1 + length) % length;  
            }  
            L1[j + 1] = L[i];  
        }  
    }  
    for (int i = 1; i <= length; i++)//  把顺序表L1中的元素依次赋值给L相应位置的元素  
    {  
        L[i] = L1[(i + first - 1) % length];    
    }    
      
}  
void main()  
{         
  SqList a= { 0, 24, 38, 50, 94, 64, 13, 25 };  
  Binpath_Insertsort(a,8);  
  for (int i = 0; i <= 8; ++i)  
    {  
        cout << a[i] << " ";  
    }  
    cout << endl;  
}  
技术分享

二路插入排序