您的位置:首页 > 编程语言 > C语言/C++

C++实现计数排序

2017-06-25 10:20 295 查看
计数排序首先利用数组计数器count[]对每个数字在数组data[]中出现的次数进行计数.然后,计数器将所有<=i的整数的个数添加并存储到count[i]中.通过这种办法,count[i]-1表明i在data[]中的主位置.

时间复杂度: 4*max value

空间复杂度: O(n),需要额外计数器存储与额外最终排序空间存储,即不是在原有数组上进行排序.

算法稳定性: 稳定

补充强化C++基础,const int * 与 int * const

const int * 指针指向的数组,数组的指针可以移动(++,–等),但数组的值不能被改动.

int* const 指针指向的数组,数组的指针不可以移动(++,–等),但数组的值可以改动.

C++ 代码如下:

头文件:

void countSort(unsigned const int* sortArray);


源文件:

template <typename T, unsigned int size>
void Sort<T, size>::countSort(unsigned const int* sortArray)
{
unsigned int *tmpArray = new unsigned int[size];
memset(tmpArray, 0, size*sizeof(unsigned int));

unsigned int max = 0;
const unsigned int* startLoc = sortArray;
//First loop, find out the max value, the max value will define count array element num
for (unsigned int i = 0; i < size; i++)
{
loopTimes++;
moveTimes++;
unsigned int value = *sortArray;
if (value > max)
{
max = value;
}
tmpArray[i] = value;
if (i == size - 1)
{

}
else
{
sortArray++;
}
}

unsigned int* countArray = new unsigned int[max+1];
memset(countArray, 0, (max+1)*sizeof(unsigned int));

sortArray = startLoc;
//Second loop, count every elem frequency
for (unsigned int i = 0; i < size; i++)
{
loopTimes++;
moveTimes++;
unsigned int value = *sortArray;
countArray[value]++;
if (i == size - 1)
{

}
else
{
sortArray++;
}
}

unsigned int culValue = 0;
//Third loop, count the elem num less and equal than each elem
for (unsigned int i = 0; i < max + 1; i++)
{
loopTimes++;
moveTimes++;
culValue = culValue + countArray[i];
countArray[i] = culValue;
}

//Fourth loop, set the value into tmpArray
for (unsigned int i = 0; i < size; i++)
{
loopTimes++;
moveTimes++;
unsigned int sortArrayTailValue = *sortArray;
tmpArray[countArray[sortArrayTailValue] - 1] = sortArrayTailValue;
countArray[sortArrayTailValue]--;
sortArray--;
}

//print tmpArray, tmp Array is sorted list
for (unsigned int i = 0; i < size; i++)
{
if ((i != 0) && (i % 8 == 0))
{
cout << endl;
}
cout << tmpArray[i] << "  ";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: