1 #include <cstdio> 2 #include <cstdint> 3 #include <ctime> 4 #include <cstring> 5 #include <cstdlib> 6 7 void GetPivot(uint8_t In_ui8A[], int64_t In_i64Begin, int64_t In_i64End) 8 { 9 uint8_t ui8Tmp = 0; 10 uint64_t ui64PivotIdx = 0; 11 if (In_ui8A == NULL || In_i64Begin >= In_i64End) 12 { 13 goto fun_ret; 14 } 15 16 ui64PivotIdx = (In_i64End - In_i64Begin + 1) / 2; 17 ui8Tmp = In_ui8A[In_i64End]; 18 In_ui8A[In_i64End] = In_ui8A[ui64PivotIdx + In_i64Begin]; 19 In_ui8A[ui64PivotIdx + In_i64Begin] = ui8Tmp; 20 fun_ret: 21 return; 22 } 23 24 void QSort(uint8_t In_ui8A[], int64_t In_i64Begin, int64_t In_i64End) 25 { 26 int64_t i = 0, j = 0; 27 uint8_t ui8Pivot = 0, ui8Tmp = 0;; 28 if (In_ui8A == NULL || In_i64Begin >= In_i64End) 29 { 30 goto fun_ret; 31 } 32 GetPivot(In_ui8A, In_i64Begin, In_i64End); 33 34 i = In_i64Begin - 1; 35 j = In_i64Begin; 36 ui8Pivot = In_ui8A[In_i64End]; 37 38 do 39 { 40 if (In_ui8A[j] <= ui8Pivot) 41 { 42 ui8Tmp = In_ui8A[++ i]; 43 In_ui8A[i] = In_ui8A[j]; 44 In_ui8A[j] = ui8Tmp; 45 } 46 j ++; 47 } while (j < In_i64End); 48 49 ui8Tmp = In_ui8A[i + 1]; 50 In_ui8A[i + 1] = ui8Pivot; 51 In_ui8A[In_i64End] = ui8Tmp; 52 53 QSort(In_ui8A, In_i64Begin, i); 54 QSort(In_ui8A, i + 2, In_i64End); 55 56 fun_ret: 57 return; 58 } 59 60 int compare (const void *p1, const void *p2) 61 { 62 if (*(uint8_t*)p1 < *(uint8_t*)p2) return -1; 63 else if (*(uint8_t*)p1 == *(uint8_t*)p2) return 0; 64 else return 1; 65 } 66 67 void main(int argc, char **argv) 68 { 69 uint8_t *pui8Buf1 = NULL, *pui8Buf2 = NULL; 70 FILE *pf = NULL; 71 long lFileSize = 0; 72 clock_t ctBegin = 0, ctQSortTime = 0, ctMyTime = 0; 73 74 pf = fopen(argv[1], "rb"); 75 fseek(pf, 0, SEEK_END); 76 lFileSize = ftell(pf); 77 fseek(pf, 0, SEEK_SET); 78 pui8Buf1 = (uint8_t *)malloc(lFileSize); 79 pui8Buf2 = (uint8_t *)malloc(lFileSize); 80 memset(pui8Buf1, 0, lFileSize); 81 memset(pui8Buf2, 0, lFileSize); 82 fread(pui8Buf1, sizeof(pui8Buf1[0]), lFileSize, pf); 83 memcpy(pui8Buf2, pui8Buf1, lFileSize); 84 fclose(pf); 85 pf = NULL; 86 87 ctBegin = clock(); 88 QSort(pui8Buf1, 0, lFileSize - 1); 89 ctMyTime = clock() - ctBegin; 90 91 ctBegin = clock(); 92 qsort((void *)pui8Buf2, lFileSize, sizeof(pui8Buf2[0]), compare); 93 ctQSortTime = clock() - ctBegin; 94 95 if (!memcmp((void *)pui8Buf1, (void *)pui8Buf2, lFileSize)) 96 { 97 printf("MyQSort::%lu\nqsort::%lu\n", ctMyTime, ctQSortTime); 98 } 99 else 100 { 101 printf("FUCK!!!\n"); 102 } 103 }
排序一個7,680字節的PE,本身實現的用了10+毫秒,qsort用了不到1毫秒,尼瑪傷自尊了。ui