实现基于数组的插入排序,选择排序,Shell排序。
插入排序,特点是移动次数多。
void InsertSort(int* start, int size)
{
int temp=0;
for(int i=1;i<size;++i)
{
temp = start[i];
int position = i;
for( ; position > 0; --position)
{
if( temp < start[position - 1])
start[position] = start[position -1];
else
break;
}
start[position] = temp;
}
}
选择排序,相对选择排序,使用了相对较少的移动次数,但是比较次数很多。
void SelectSort(int* start, int size)
{
for(int i=size-1;i>0;--i)
{
int largest = 0;
for(int j=1; j<= i; ++j)
{
if(start[largest] < start[j])
largest = j;
}
if( largest != i )
{
int temp = start[i];
start[i] = start[largest];
start[largest] = temp;
}
}
}
void ShellSort(int* start, int size)
{
int step = size;
do
{
step = step / 3 + 1;
for(int i=0;i<step;++i)
ShellInsertSort(start+i,size-i,step);
}while(step > 1);
}
void ShellInsertSort(int* start,int size,int step)
{
int temp =0;
for(int i=step;i<size;i+=step)
{
temp = start[i];
int position = i;
for( ; position > 0; position-=step)
{
if( temp < start[position - step])
start[position] = start[position -step];
else
break;
}
start[position] = temp;
}
}
void TestSort(int number,int max,string tag ,void (*SortFunc)(int*,int))
{
srand(time(NULL));
int* list = new int[number];
for(int i=0;i<number;++i)
list[i] = GenerateRandomNumber(max);
DoTestSort(tag,list,number,SortFunc);
}
void TestSort(int number,int max)
{
TestSort(number,max,"Insert Sort",InsertSort);
TestSort(number,max,"Select Sort",SelectSort);
TestSort(number,max,"Shell Sort",ShellSort);
}
void DoTestSort(string tag, int* list,int size, void (*SortFunc)(int*,int))
{
cout << tag << " test" << endl;
PrintList(list,size);
SortFunc(list,size);
cout << "IsInOrder=" << IsInOrder(list,size) << endl;
PrintList(list,size);
}
int GenerateRandomNumber(int max)
{
return rand() % max + 1;
}
void PrintList(int* start, int size)
{
for(int i=0;i<size;++i)
cout<< start[i] << ",";
cout << endl;
}
bool IsInOrder(int* start, int size)
{
for(int i=0;i<size-1;++i)
{
if(start[i] > start[i+1])
return false;
}
return true;
}
还有一个简单的类似排序,冒泡排序,代码如下:
void PopSort(int* pData,int length)
{
bool change = true;
int temp = 0;
for(int i=0;i<length-1 && change;++i)
{
change = false;
for(int k=length-1;k>i;--k)
{
if(pData[k] < pData[k-1])
{
temp = pData[k];
pData[k] = pData[k-1];
pData[k-1] = temp;
change = true;
}
}
}
}