Saturday, December 17, 2011

Insertion Sort

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AlgorithmTestCase {

        protected Logger logger = LoggerFactory.getLogger(getClass());

        @Test
        public void insertionSortTest() {
                final int[] array = { -9, 9, 8, 7, 6, 5, 4, -8, 3, 2, 1, 0, 8945121 };

                int[] order = insertionAscSort(array);
                show(order);

                final int[] desc = insertionDescSort(array);
                show(desc);
        }

        private final int[] insertionAscSort(int[] array) {

                int i, j, elemento;

                for (i = 1; i < array.length; i++) {

                        elemento = array[i];

                        for (j = i - 1; j >= 0 && array[j] > elemento; j--) {
                                array[j + 1] = array[j];
                                array[j] = elemento;
                        }

                }

                return array;
        }

        private final int[] insertionDescSort(int[] array) {

                int i, j, elemento;

                for (i = 1; i < array.length; i++) {

                        elemento = array[i];

                        for (j = i - 1; j >= 0 && array[j] < elemento; j--) {
                                array[j + 1] = array[j];
                                array[j] = elemento;
                        }

                }

                return array;
        }

        private final void show(int[] array) {
                logger.info("Result");
                for (int i = 0; i < array.length; i++) {
                        logger.info("Array: " + array[i]);
                }
        }

}

No comments: