Download code

Jump to: navigation, search

Back to Radix_sort_(C)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

radixsort.c

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Radix_sort_(C)?oldid=4760
14 */
15 
16 #include<stdlib.h>
17 #include<stdio.h>
18 #include<assert.h>
19 #include<limits.h>
20 #include<strings.h>
21 #include<string.h>
22 void radix_sort_uint(unsigned int *a, size_t size, int bits)
23 {
24 	unsigned int mask;
25 	unsigned int rshift=0u;
26 	unsigned int *p, *b, *b_orig;
27 	unsigned int i;
28 	unsigned int key;
29 	int cntsize;
30 	int *cntarray;
31 	b=b_orig=malloc(size*sizeof(unsigned int));
32 	cntsize=1u<<bits;
33 	cntarray=calloc(cntsize, sizeof(int));
34 
35 	assert(cntarray);
36 	assert(b_orig);
37 
38 	for(mask=~(UINT_MAX<<bits); mask; mask<<=bits, rshift+=bits) {
39 		for(p=a; p<a+size; ++p) {
40 			key=(*p & mask)>>rshift;
41 			++cntarray[key];
42 		}
43 
44 		for(i=1; i<cntsize; ++i) cntarray[i]+=cntarray[i-1];
45 
46 		for(p=a+size-1; p>=a; --p) {
47 			key=(*p & mask)>>rshift;
48 			b[cntarray[key]-1]=*p;
49 			--cntarray[key];
50 		}
51 
52 		p=b; b=a; a=p;
53 
54 		bzero(cntarray, cntsize * sizeof(int));
55 	}
56 
57 	if(a==b_orig) memcpy(b, a, size*sizeof(unsigned int));
58 
59 	free(b_orig);
60 	free(cntarray);
61 }
62 
63 int main()
64 {
65 	int i;
66 	unsigned int a[]={
67 		123,432,654,3123,654,2123,543,131,653,123,
68 		533,1141,532,213,2241,824,1124,42,134,411,
69 		491,341,1234,527,388,245,1992,654,243,987};
70 
71 	printf("Before radix sort:\n");
72 	for(i=0; i<sizeof a/sizeof(unsigned int); ++i) 
73 		printf(" %d", a[i]);
74 	putchar('\n');
75 
76 	radix_sort_uint(a, sizeof a/sizeof(int), 4);
77 
78 	printf("After radix sort:\n");
79 	for(i=0; i<sizeof a/sizeof(unsigned int); ++i) 
80 		printf(" %d", a[i]);
81 	putchar('\n');
82 
83 	return 0;
84 }
85 


hijacker
hijacker
hijacker
hijacker