|
| 1 | +// Patrick Yevsukov |
| 2 | + |
| 3 | +// 2013 CC BY-NC-SA 4.0 http://patrick.yevsukov.com |
| 4 | + |
| 5 | +// github.com/PatrickYevsukov/Sorting-Algorithms |
| 6 | + |
| 7 | +public static void RadixSort(ArrayList<Integer> list) { |
| 8 | + |
| 9 | + final int NUM_BASE = 10; |
| 10 | + |
| 11 | + int maximum = 0; |
| 12 | + |
| 13 | + ArrayList<ArrayList<Integer>> buckets; |
| 14 | + |
| 15 | + buckets = new ArrayList<ArrayList<Integer>>(NUM_BASE); |
| 16 | + |
| 17 | + // New buckets are added to the bucket list; one for each digit |
| 18 | + // in the numeral system of the data being sorted. |
| 19 | + |
| 20 | + for (int ii = 0; ii < NUM_BASE; ii++) { |
| 21 | + |
| 22 | + buckets.add(new ArrayList<Integer>()); |
| 23 | + } |
| 24 | + |
| 25 | + // Identifying the list item with the most place values. |
| 26 | + |
| 27 | + for (int ii = 0; ii < list.size(); ii++) { |
| 28 | + |
| 29 | + if (list.get(ii) > maximum) { |
| 30 | + |
| 31 | + maximum = list.get(ii); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + // List items are sorted by place value. The place value is |
| 36 | + // multiplied by the numeric base with each pass of the loop. |
| 37 | + |
| 38 | + for (int power = 1; maximum / power != 0; power *= NUM_BASE) { |
| 39 | + |
| 40 | + for (int ii = 0; ii < list.size(); ii++) { |
| 41 | + |
| 42 | + // List items are added to the bucket which corresponds |
| 43 | + // to the place value which they are being sorted by. |
| 44 | + |
| 45 | + buckets.get(list.get(ii) / power % NUM_BASE) |
| 46 | + .add(list.get(ii)); |
| 47 | + } |
| 48 | + |
| 49 | + int index = 0; |
| 50 | + |
| 51 | + for (int ii = 0; ii < buckets.size(); ii++) { |
| 52 | + |
| 53 | + for (int jj = 0; jj < buckets.get(ii).size(); jj++) { |
| 54 | + |
| 55 | + // The buckets, sorted by the current place value |
| 56 | + // under consideration, have their values written |
| 57 | + // back to original list, overwriting its previous |
| 58 | + // contents. |
| 59 | + |
| 60 | + list.set(index, buckets.get(ii).get(jj)); |
| 61 | + index++; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + // At the end of each pass of the loop, the contents of the |
| 66 | + // buckets are dumped out. |
| 67 | + |
| 68 | + for (int ii = 0; ii < buckets.size(); ii++) { |
| 69 | + |
| 70 | + buckets.get(ii).clear(); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +// Above is my implementation of a radix sort. I |
| 76 | +// wrote it to be as human readable as possible. |
0 commit comments