/* 1.全部是升序排列 */ #include <stdlib.h> #include <string> #include <ctime> #include <Windows.h> class QTimer { public: LARGE_INTEGER t1, t2, tc; public: QTimer() { QueryPerformanceFrequency(&tc); } void Start() { QueryPerformanceCounter(&t1); } void Stop() { QueryPerformanceCounter(&t2); } void Show() { // printf("Begin Time: %u/n", t1.QuadPart); // printf("End Time: %u/n", t2.QuadPart); // printf("Lasting Time: %u/n",( t2.QuadPart- t1.QuadPart)); // 这里要计算时间(单位为秒),应加上这一句 double dTotalTime = (double)(t2.QuadPart-t1.QuadPart) / (double)tc.QuadPart; //秒 printf("耗时: %f s/n", dTotalTime); system("pause"); } }; UINT g_uiData[10001]={0}; void InitData() { FILE *f=fopen("temp.txt","r"); int i=0; for (i=1;i<10001;i++) { fscanf(f,"%d/n",&g_uiData[i]); } fclose(f); } void Show() { int i=0; for (i=1;i<10001;i++) { printf("%d/n",g_uiData[i]); } } /* 1.直接插入排序 2.要求部分有序 */ void StraightInsertionSort() { int ixIndex,iyIndex; QTimer qt; qt.Start(); for (ixIndex=2;ixIndex<=10000;ixIndex++)//从头开始比较 { if (g_uiData[ixIndex-1]>g_uiData[ixIndex])//如果相邻两个数,左边>右边,进入If { g_uiData[0]=g_uiData[ixIndex];//则将较小的数拷贝到哨兵位置 iyIndex=ixIndex;//开始后移数组位置 for (;g_uiData[0]<g_uiData[iyIndex-1];iyIndex--)//如果哨兵值小于索引的数组值,则后移结束 { g_uiData[iyIndex]=g_uiData[iyIndex-1]; } g_uiData[iyIndex]=g_uiData[0];//将哨兵值拷贝到正确位置 } } qt.Stop(); qt.Show(); } /* 1.折半插入排序 2.折半查找找到插入位置,然后进行后移 3.要求部分有序 */ void BInsertionSort() { int iLeft,iRight; int iXIndex,iYIndex; QTimer qt; iLeft=0; iRight=0; int iTemp; qt.Start(); for (iXIndex=2;iXIndex<=10000;iXIndex++) { if (g_uiData[iXIndex-1]>g_uiData[iXIndex]) { g_uiData[0]=g_uiData[iXIndex]; iLeft=1;iRight=iXIndex-1; while(iLeft<=iRight)//循环结束,得到插入位置iLeft或者iRight-1 { iTemp=(iLeft+iRight)/2; if (g_uiData[0]<g_uiData[iTemp]) { iRight=iTemp-1; } else iLeft=iTemp+1; } for (iYIndex=iXIndex;iYIndex-1>=iLeft;iYIndex--)//后移 { g_uiData[iYIndex]=g_uiData[iYIndex-1]; } g_uiData[iLeft]=g_uiData[0]; } } qt.Stop(); qt.Show(); } int _tmain(int argc, _TCHAR* argv[]) { InitData(); StraightInsertionSort(); InitData(); BInsertionSort(); Show(); return 0; }