1 // CmpTest.cpp : Defines the entry point for the console application. 2 // 3 4 #include "stdafx.h" 5 6 #include <string.h> 7 template <class T, class CMP_FUN> 8 bool MySort(T* psArray, int i4Num, CMP_FUN CmpFun); 9 10 typedef struct __MYTEST__ 11 { 12 int a; 13 int b; 14 } S_MYTEST; 15 16 //a>b 从小到大 17 bool Cmp2(S_MYTEST &a, S_MYTEST &b) 18 { 19 return (a.a > b.a); 20 } 21 22 //a>b 从大到小 23 bool Cmp3(int &a, int &b) 24 { 25 return (a < b); 26 } 27 28 29 int main(int argc, char* argv[]) 30 { 31 int array[10] = {1,2,3,4,6,7,5}; 32 MySort(array, 10, Cmp3); 33 34 S_MYTEST stMyTest[5] = {{1,2},{0,3},{10,9},{11,8},{23,1}}; 35 MySort(stMyTest, 5, Cmp2); 36 37 return 0; 38 } 39 40 41 //选择排序 42 template <class T, class CMP_FUN> 43 bool MySort(T* psArray, int i4Num, CMP_FUN CmpFun) 44 { 45 int i4Count = 1;//次数 46 int i4Index = 0; //索引 47 48 T *psSelElement = 0; //记录的元素(最大或者最小) 49 T TempElement; //临时变量,用于数据交换 50 memset(&TempElement, 0, sizeof(T)); 51 52 //查找符合条件的元素 保存在 psSelElement 53 for (i4Count = 1; i4Count < i4Num; i4Count++) 54 { 55 psSelElement = &psArray[0]; //初始为第一个元素 56 for (i4Index = 1; i4Index <= i4Num - i4Count; i4Index++) 57 { 58 if (NULL == psSelElement) 59 { 60 return false; 61 } 62 if (CmpFun(psArray[i4Index], *psSelElement)) 63 { 64 psSelElement = &psArray[i4Index];//修改为满足要求的元素 65 } 66 } 67 68 //将psSelElement 替换到 最后的位置(i4Num - i4Count) 69 if (psSelElement != &psArray[i4Num - i4Count]) 70 { 71 memcpy(&TempElement, &psArray[i4Num - i4Count], sizeof(T)); 72 memcpy(&psArray[i4Num - i4Count], psSelElement, sizeof(T)); 73 if (NULL == psSelElement) 74 { 75 return false; 76 } 77 memcpy(psSelElement, &TempElement, sizeof(T)); 78 } 79 } 80 81 return true; 82 }