直接插入排序,一般實作都是對int型資料進行排序,如果我需要對double數組、string數組呢?
下面是一個利用void指針進行的類型無關插入排序
<code>#include<iostream> #include<malloc.h> //malloc #include<string.h> //memcpy #include<string> #include<iterator> //iterator_traits using std::endl; using std::cout; using std::string; using std::vector; bool intLess(void *x, void *y){ return *((int *)x) < *((int *)y); } bool doubleLess(void *x, void *y){ return *((double *)x) < *((double *)y); } bool stringLess(void *x, void *y){ return *((string *)x) < *((string *)y); } void insertSort(void *arr, //待排序數組 const int length, //數組長度 const size_t elemSize, //數字元素大小 bool (*less)(void *, void *)){ //小于比較器 void *elemToInsert = (void *)malloc(elemSize); for(int i=1; i<length; ++i){ int j = 0; memcpy(elemToInsert, (char *)arr + i * elemSize, elemSize); for(j=i-1; j>=0; --j){ if(less(elemToInsert, ((char*)arr + (j*elemSize)))) memcpy((char*)arr + (j+1) * elemSize, (char*)arr + j * elemSize, elemSize); else break; } memcpy((char*)arr + (j+1) * elemSize, elemToInsert, elemSize); } free(elemToInsert); } template<class Iterator> void displayArr(const Iterator &beg, const Iterator &end){ typedef typename std::iterator_traits<Iterator>::value_type Ty; std::copy(beg, end, std::ostream_iterator<Ty>(std::cout," ")); cout<<endl; } int main(int argc, char **argv){ int intArr[] = { 12, 0, -65, 12, 2, 98, -7821 }; double doubleArr[] = { -3.0, -45.5, 12.3, 0.1, 26.6, -45.7 }; string stringArr[] = {"月夜幻影", "C++", "月夜","51CTO", "billhoo", "Billhoo", "C", "Alex" }; cout<<"排序前:"<<endl; displayArr<int *>(intArr, intArr + sizeof(intArr)/sizeof(*intArr)); displayArr<double *>(doubleArr, doubleArr + sizeof(doubleArr)/sizeof(*doubleArr)); displayArr<string *>(stringArr, stringArr + sizeof(stringArr)/sizeof(*stringArr)); //開始插入排序 insertSort(intArr, sizeof(intArr)/sizeof(*intArr), sizeof(int), intLess); insertSort(doubleArr, sizeof(doubleArr)/sizeof(*doubleArr), sizeof(double), doubleLess); insertSort(stringArr, sizeof(stringArr)/sizeof(*stringArr), sizeof(string), stringLess); cout<<"\n排序後:"<<endl; displayArr<int *>(intArr, intArr + sizeof(intArr)/sizeof(*intArr)); displayArr<double *>(doubleArr, doubleArr + sizeof(doubleArr)/sizeof(*doubleArr)); displayArr<string *>(stringArr, stringArr + sizeof(stringArr)/sizeof(*stringArr)); }</code>
本文轉自Bill_Hoo 51CTO部落格,原文連結:http://blog.51cto.com/billhoo/789196,如需轉載請自行聯系原作者