基數(shù)排序與基數(shù)排序是兩種非比較型排序。
創(chuàng)新互聯(lián)2013年開創(chuàng)至今,是專業(yè)互聯(lián)網(wǎng)技術(shù)服務(wù)公司,擁有項(xiàng)目成都網(wǎng)站制作、成都做網(wǎng)站網(wǎng)站策劃,項(xiàng)目實(shí)施與項(xiàng)目整合能力。我們以讓每一個(gè)夢(mèng)想脫穎而出為使命,1280元阿魯科爾沁做網(wǎng)站,已為上家服務(wù),為阿魯科爾沁各地企業(yè)和個(gè)人服務(wù),聯(lián)系電話:028-86922220
計(jì)數(shù)排序:
//************計(jì)數(shù)排序********* //先最大-最小+1得到開辟空間數(shù),開辟空間str,在遍歷原數(shù)據(jù)arr在str相應(yīng)位置計(jì)數(shù),再遍歷str將值寫到原arr中 //適用在密集型數(shù)據(jù), 無(wú)重復(fù)最優(yōu)可轉(zhuǎn)化為位圖 //時(shí)間復(fù)雜度O(N),空間復(fù)雜度O(最大數(shù)-最小數(shù)+1) //設(shè)數(shù)組元素非負(fù) void CountingSort(int *a, size_t size) { size_t i = 0, j = 0; int max = a[0], min = a[0]; size_t space = 0; for (i = 1; i < size; i++) { if (max < a[i]) { max = a[i]; } if (min > a[i]) { min = a[i]; } } space = max - min + 1; //str相應(yīng)位置記錄a中個(gè)數(shù)據(jù)的次數(shù) int *str = new int[space](); for (i = 0; i < size; i++) { str[a[i] - min] ++; } //寫回原數(shù)組a中 for (i = 0, j = 0; i < space, j < size; i++) { while (str[i]-- > 0) { a[j++] = i + min; } } }
基數(shù)排序:
//***********基數(shù)排序************** //采用先排低位,在排高位 //時(shí)間復(fù)雜度O(位數(shù)) 空間復(fù)雜度O(N) //設(shè)數(shù)組元素非負(fù) size_t GetMaxRadix(int *a, size_t size)//取數(shù)組中最大值的位數(shù) { assert(a != NULL); size_t i = 0; size_t num = 0; size_t count = 1; for (i = 0; i < size; i++) { while (a[i] / count>0) { count *= 10; num++; } } return num; } void LSDSort(int *a, size_t size) { assert(a != NULL); int MaxRadix = GetMaxRadix(a, size); int count[10] = { 0 };//同一位上數(shù)字相等的數(shù)字個(gè)數(shù) int start[10] = { 0 };//按位上數(shù)字所對(duì)應(yīng)的起始位置 int * bucket = new int[size]; size_t i = 0; int num = 1; while (MaxRadix--) { memset(count, 0, sizeof(int) * 10);//count清零 //按位排序 for (i = 0; i < size;i++)//count[] { count[a[i] / num % 10]++;//取某一位上數(shù)字,在count相應(yīng)位置++ } for (i = 0; i < 10; i++)//start[] { //跳過0 因?yàn)槠鹗嘉恢靡欢? if (i == 0) { start[i] = 0; } else start[i] = start[i - 1] + count[i - 1]; } //寫到bucket[]中 for (i = 0; i < size; i++) { bucket[start[a[i] / num % 10]++] = a[i]; } //寫回a[]中 for (i = 0; i < size; i++) { a[i] = bucket[i]; } num *= 10; } }
test:
int a5[] = { 5, 24, 35, 54, 72, 81, 75, 6, 9, 56, 114, 30, 5 }; int a6[] = { 5, 24, 35, 54, 72, 81, 75, 6, 9, 56, 114, 30, 5 };