直接插入排序,一般实现都是对int型数据进行排序,如果我需要对double数组、string数组呢?
下面是一个利用void指针进行的类型无关插入排序
代码:
#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));
}
转载于:https://blog.51cto.com/billhoo/789196