对于一个int数组,请编写一个计数排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
计数排序
class CountingSort { public: int* countingSort(int* A, int n) { // write code here int min=A[0],max=A[0]; for(int i=1;i<n;i++) { if(A[i]<min) min=A[i]; if(A[i]>max) max=A[i]; } int k=max-min+1; int* B=new int[k](); //初始化为0 for(int i=0;i<n;i++) B[A[i]-min]++; int idx=0; for(int i=min;i<=max;i++) for(int j=0;j<B[i-min];j++) A[idx++]=i; delete []B; return A; } };
对于一个int数组,请编写一个基数排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。保证元素均小于等于2000。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
基数排序
#include <iostream> using namespace std; const int MAX = 10; void print(int *a, int sz) { for (int i = 0; i < sz; i++) cout << a[i] << " "; cout << endl; } void RadixSortLSD(int *a, int arraySize) { int i, bucket[MAX], maxVal = 0, digitPosition = 1; for (i = 0; i < arraySize; i++) { if (a[i] > maxVal) maxVal = a[i]; } int pass = 1; // used to show the progress /* maxVal: this variable decide the while-loop count if maxVal is 3 digits, then we loop through 3 times */ while (maxVal / digitPosition > 0) { /* reset counter */ int digitCount[10] = { 0 }; //对每一位:统计0-10对于数字的个数 /* count pos-th digits (keys) */ for (i = 0; i < arraySize; i++) digitCount[a[i] / digitPosition % 10]++; /* accumulated count */ for (i = 1; i < 10; i++) digitCount[i] += digitCount[i - 1]; /* To keep the order, start from back side */ for (i = arraySize - 1; i >= 0; i--) { int temp = a[i] / digitPosition % 10; bucket[--digitCount[temp]] = a[i]; } /* rearrange the original array using elements in the bucket */ for (i = 0; i < arraySize; i++) a[i] = bucket[i]; /* at this point, a array is sorted by digitPosition-th digit */ cout << "pass #" << pass++ << ": "; print(a, arraySize); /* move up the digit position */ digitPosition *= 10; } }