标签:排序
/归并[)升序 //使用链表合并思想 void Merge(int* src, int* dest, int begin1, int end1, int begin2, int end2) { assert(src&&dest); int index = begin1;//两个区间挨着 while (begin1 < end1&&begin2 < end2) { if (src[begin1] < src[begin2]) { dest[index++] = src[begin1++]; } else { dest[index++] = src[begin2++]; } } if (begin1 < end1) { while (begin1 < end1) dest[index++] = src[begin1++]; } else { while (begin2 < end2) dest[index++] = src[begin2++]; } } void _MergeSort(int* src, int* dst, int left, int right) { if (left < right - 1)//[) { int mid = left + ((right - left) >> 1); _MergeSort(src, dst, left, mid); _MergeSort(src, dst, mid, right); Merge(src, dst, left, mid, mid, right); memcpy(src + left, dst + left, sizeof(int)*(right - left)); } } void MergeSort(int *a, size_t size) { int *dest = new int[size]; _MergeSort(a, dest, 0, 10); delete[] dest; } //非比较排序:基数与计数 //基数排序:利用哈希桶原理把数据排序,可选择从低位到高位或从高位到低位 //利用稀疏矩阵压缩存储进行数据定位 int GetDigit(int* arr, size_t size) { int maxDigit = 1; int maxNum = 10; for (int i = 0; i < size; ++i) { if (arr[i] >= maxNum) { int count = maxDigit; while (maxNum <= arr[i]) { maxNum *= 10; ++count; } maxDigit = count; } } return maxDigit; } void LSDSort(int* arr, size_t size)//从低位开始排 MSD从高位开始排 { int counts[10] = { 0 };//存位数对应数据个数 int startCounts[10] = { 0 }; int *bucket = new int[size]; int digit = 1;//表示先取各位 int maxDigit = GetDigit(arr, size); int divider = 1;//除数 while (digit++ <= maxDigit) { memset(counts, 0, sizeof(int) * 10); memset(startCounts, 0, sizeof(int) * 10); for (int i = 0; i < size; ++i) counts[(arr[i]/divider)% 10]++; for (int i = 1; i < 10; ++i) startCounts[i] = startCounts[i - 1] + counts[i - 1]; for (int i = 0; i < size; ++i) { bucket[startCounts[(arr[i] / divider) % 10]++] = arr[i]; } divider *= 10; memcpy(arr, bucket, sizeof(int)*size); } memcpy(arr, bucket, sizeof(int)*size); delete[] bucket; } void CountSort(int *arr, size_t size,int len) { int* bitMap = new int[len]; memset(bitMap, 0, sizeof(int)*len); for (int i = 0; i < size; ++i) { int index = arr[i] >>5;//除以32 int count = arr[i] % 32; bitMap[index] |= (1 << count); } int index = 0; for (int i = 0; i < len; ++i) { int count = 0; while (count <32&&index<size ) { if (bitMap[i] & (1 << count)) arr[index++] = i * 32 + count; ++count; } } delete[] bitMap; }
本文出自 “小止” 博客,请务必保留此出处http://10541556.blog.51cto.com/10531556/1757205
标签:排序
原文地址:http://10541556.blog.51cto.com/10531556/1757205