Matakuliah Tahun Versi : T0016/Algoritma dan Pemrograman : 2005 : versi 2 Pertemuan 22 Radix Sort 1 Learning Outcomes Pada akhir pertemuan ini, diharapkan mahasiswa akan mampu : • Menjelaskan teknik radix sort 2 Outline Materi • Pengenalan radix sort 3 Radix Sort Definition : • A multiple pass distribution sort algorithm that distributes each item to a bucket according to part of the item's key beginning with the least significant part of the key. After each pass, items are collected from the buckets, keeping the items in order, then redistributed according to the next most significant part of the key. 4 Radix Sort • Here is a simple example of the sort. Suppose the input keys are 34, 12, 42, 32, 44, 41, 34, 11, 32, and 23. • Four buckets are appropriate. The first pass distributes them by the least significant digit. After the first pass we have the following, where each line is a bucket. 41 11 12 42 32 32 23 34 44 34 • We collect these, keeping their relative order: 41 11 12 42 32 32 23 34 44 34. Now we distribute by the next most significant digit, in this case, the highest digit, and we get the following. 11 12 23 32 32 34 34 41 42 44 When we collect them, they are in order: 11 12 23 32 32 34 34 41 42 44. 5 Contoh void radix (int byte, long N, long *source, long *dest) { long count[256]; long index[256]; memset (count, 0, sizeof (count)); for ( int i=0; i<N; i++ ) count[((source[i])>>(byte*8))&0xff]++; index[0]=0; for ( i=1; i<256; i++ ) index[i]=index[i-1]+count[i-1]; for ( i=0; i<N; i++ ) dest[index[((source[i])>>(byte*8))&0xff]++] = source[i]; } void radixsort (long *source, long *temp, long N) { radix (0, N, source, temp); radix (1, N, temp, source); radix (2, N, source, temp); radix (3, N, temp, source); } void make_random (long *data, long N) { for ( int i=0; i<N; i++ ) data[i]=rand()|(rand()<<16); } long data[100]; long temp[100]; void main (void) { make_random(data, 100); radixsort (data, temp, 100); for ( int i=0; i<100; i++ ) cout << data[i] << '\n'; } 6 LSD Radix Sort 7 Contoh MSD Radix Sort 8 Penutup Radix Sort makes several passes of the previous Counting Sort in order to completely sort integer keys. Counting Sort can be used as the intermediate sorting routine because it provides a stable sort. 9