/*
今天学习counting sort,下面是c的counting sort实现。。
这个版本比较简单,只能排 大于等于0的array,有负数的情况还要做一些改变。
需要注意的是,这个版本是一个 non-stable sorting 因为最后一个for loop,是从array的左边开始的,
对于这个例子stable或者non-stable都不重要,但如果要把counting sort作为radix sort的子程序的话,
就一定要保证最后一个loop是从array的右边开始,这样可以保证它一定是stable的。
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// finds max value of a given array.
int max(int *array, int SIZE) {
int m = array[0];
for (int i=1; i<SIZE; ++i) {
if (array[i] > m) {
m = array[i];
}
}
return m;
}
int * countSort(int *array, int SIZE) {
// finds upperbound
int MAX = max(array, SIZE);
// sets up the array for holding the count
int count[MAX + 1];
// this array is for output
int *output = (int*) malloc(sizeof(int) * SIZE);
// initilizes both arrays to all-0
memset(count, 0, (MAX+1) * sizeof(int));
memset(output, 0, SIZE * sizeof(int));
// counts occurrence of element in to-be-sorted array
for (int i=0; i<SIZE; i++) {
count[array[i]] ++;
}
// sums up occurrence towards right
// the value means the correct position an element should be.
for (int i=1; i<(MAX+1); i++) {
count[i] += count[i-1];
}
// sorts the array through mapping from count array.
for (int j=0; j<SIZE; ++j) {
output[count[array[j]] - 1] = array[j];
count[array[j]] --;
}
return output;
}
int main()
{
// array to be sorted.
int arr[] = {4, 9, 2, 4, 7, 6};
int SIZE = sizeof(arr) / sizeof(int);
int *result = countSort(arr, SIZE);
// prints out sorted array.
for (int i=0; i<SIZE; i++){
printf("%d ", result[i]);
}
printf("\n");
free(result);
return 0;
}
counting sort 计数排序 c语言实现
最新推荐文章于 2024-06-23 10:28:39 发布