1. 程式人生 > >二路插入排序

二路插入排序

ast content main track [1] gravity std names http

#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;  
}  
技術分享

二路插入排序