001package template.sort;
002
003/* This example is from Robert C. Martin */
004abstract class BubbleSorter {
005        private int operations = 0;
006        protected int length = 0;
007        protected int doSort() {
008                operations = 0;
009                if (length <= 1) return operations;
010                for (int nextToLast = length-2; nextToLast >= 0; nextToLast--)
011                        for (int index = 0; index <= nextToLast; index++) {
012                                if (outOfOrder(index)) swap(index);
013                                operations++;
014                        }
015                return operations;
016        }
017        protected abstract void swap(int index);
018        protected abstract boolean outOfOrder(int index);
019}
020
021class IntBubbleSorter extends BubbleSorter {
022        private int[] array = null;
023        public int sort(int [] array) {
024                this.array = array;
025                this.length = array.length;
026                return doSort();
027        }
028        protected void swap(int index) {
029                int temp = array[index];
030                array[index] = array[index+1];
031                array[index+1] = temp;
032        }
033        protected boolean outOfOrder(int index) {
034                return (array[index] > array[index+1]);
035        }
036}
037
038class DoubleBubbleSorter extends BubbleSorter {
039        private double[] array = null;
040        public int sort(double [] array) {
041                this.array = array;
042                this.length = array.length;
043                return doSort();
044        }
045        protected void swap(int index) {
046                double temp = array[index];
047                array[index] = array[index+1];
048                array[index+1] = temp;
049        }
050        protected boolean outOfOrder(int index) {
051                return (array[index] > array[index+1]);
052        }
053}