|
| 1 | +/* |
| 2 | + * To change this template, choose Tools | Templates |
| 3 | + * and open the template in the editor. |
| 4 | + */ |
| 5 | +package array.visualizer.sort; |
| 6 | + |
| 7 | +import array.visualizer.ArrayController; |
| 8 | + |
| 9 | +import static array.visualizer.ArrayVisualizer.*; |
| 10 | +import static array.visualizer.utils.Analysis.*; |
| 11 | +import static array.visualizer.utils.Swaps.*; |
| 12 | + |
| 13 | +/** |
| 14 | + * |
| 15 | + * @author Skeen |
| 16 | + */ |
| 17 | +public class BinaryQuickSort implements Sort { |
| 18 | + |
| 19 | + public static boolean getBit(int n, int k) { |
| 20 | + // Find boolean value of bit k in n |
| 21 | + return ((n >> k) & 1) == 1; |
| 22 | + } |
| 23 | + |
| 24 | + public static int analyzeBit(final ArrayController ac) { |
| 25 | + // Find highest bit of highest value |
| 26 | + int max = 0; |
| 27 | + for(int i = 0; i < ac.length; i++){ |
| 28 | + ac.marked.set(1, i); |
| 29 | + ac.aa++; |
| 30 | + sleep(1); |
| 31 | + max = Math.max(max, ac.array[i]); |
| 32 | + } |
| 33 | + return 31 - Integer.numberOfLeadingZeros(max); |
| 34 | + } |
| 35 | + |
| 36 | + public static void binaryQuickSort(final ArrayController ac, int p, int r, int bit) |
| 37 | + { |
| 38 | + if (p < r && bit >= 0) |
| 39 | + { |
| 40 | + int q=partition(ac, p, r, bit); |
| 41 | + sleep(1); |
| 42 | + binaryQuickSort(ac, p, q, bit-1); |
| 43 | + binaryQuickSort(ac, q+1, r, bit-1); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + public static int partition(final ArrayController ac, int p, int r, int bit) |
| 48 | + { |
| 49 | + int i = p - 1; |
| 50 | + int j = r + 1; |
| 51 | + |
| 52 | + while (true) { |
| 53 | + // Left is not set |
| 54 | + i++; |
| 55 | + while(i < r && !getBit(ac.array[i], bit)) { |
| 56 | + i++; |
| 57 | + ac.marked.set(1, i); |
| 58 | + sleep(0.45); |
| 59 | + ac.comps+=2; |
| 60 | + } |
| 61 | + // Right is set |
| 62 | + j--; |
| 63 | + while(j > p && getBit(ac.array[j], bit)) { |
| 64 | + j--; |
| 65 | + ac.marked.set(2, j); |
| 66 | + sleep(0.45); |
| 67 | + ac.comps+=2; |
| 68 | + } |
| 69 | + // If i is less than j, we swap, otherwise we are done |
| 70 | + if (i < j) |
| 71 | + swap(ac, i, j); |
| 72 | + else |
| 73 | + return j; |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + @Override |
| 78 | + public String name() |
| 79 | + { |
| 80 | + return "Binary Quicksort"; |
| 81 | + } |
| 82 | + |
| 83 | + @Override |
| 84 | + public void sort(ArrayController ac) |
| 85 | + { |
| 86 | + int msb = analyzeBit(ac); |
| 87 | + binaryQuickSort(ac, 0, ac.length-1, msb); |
| 88 | + } |
| 89 | +} |
0 commit comments