2-路插入排序 一个简单示例

来源:互联网 发布:js中的unshift 编辑:程序博客网 时间:2024/05/21 10:20
//a example of 2-way insertion sort#include <stdio.h>#include <stdlib.h>int iList[] = {1, 4, 2, 12, 4, 34, 243, 11, 35};void TwoWayInsert(int iList[], int iLen)//iLen is the length of iList{int i, j;int first = 0;//pointer point to the first recordint final = 0;//pointer point to the final recordint *iTemp = NULL;if((iTemp = (int *) malloc(iLen * sizeof(int))) == NULL)//Dynamic allocation of space{fprintf(stderr, "allocate space error !");exit(1);}//printf("%d\n", sizeof(iList) / sizeof(iList[0]));because iList is a pointer, so this is wrong    iTemp[0] = iList[0];//copy fisrt element of iListfor(i = 1; i < iLen; i++)//start from the second{if(iList[i] >= iTemp[final]){iTemp[++final] = iList[i];}else if(iList[i] <= iTemp[first]){first = (first - i + iLen) % iLen;//first point to the end of iList firstlyiTemp[first] = iList[i];//copy to iTemp[first]}else//insert when the element is bigger than iList[i] and smaller than iList[final]{//use binary sort insertion int iLow, iHigh;int iMid;int iFlag;//identify the side of insertionif(iList[i] < iTemp[0])//make sure the value of low and high{iLow = first;iHigh = iLen - 1;iFlag = 1;}else{iLow = 0;iHigh = final;iFlag = 0;}while(iLow <= iHigh)//it must have equal signal{iMid = (iLow + iHigh) / 2;if(iList[i] <=  iTemp[iMid])//Does it must have equal signal?no matter {iHigh = iMid - 1;}else{iLow = iMid + 1;}}//find the location to insert if(iFlag == 0){for(j = final; j >= iHigh + 1; --j)//backword the other element{iTemp[j + 1] = iTemp[j];}final++;iTemp[iHigh + 1] = iList[i];}else{for(j = first; j <= iHigh; j++)//forword the other element{iTemp[j - 1] = iTemp[j];}first--;iTemp[iHigh +  1] = iList[i];}}}j = 0;for(i = first; i < iLen; i++){iList[j++] = iTemp[i];}for(i = 0; i <= final; i++){iList[j++] = iTemp[i];}}int main(void){int i;int iLen;iLen = sizeof(iList) / sizeof(iList[0]);//printf("%d\n", iLen);TwoWayInsert(iList , iLen);for(i = 0; i < iLen; i++){printf((i == iLen - 1) ? "%d\n" : "%d, ", iList[i]);}return 0;}