R
R
rsatarov2016-10-28 00:14:34
Java
rsatarov, 2016-10-28 00:14:34

Is it possible to optimize sorting?

Found a specific algorithm called "Circle Sort". It compares the extreme elements of the array, gradually reaching the middle, and then recursively sorts its smaller parts. True, he does not always do everything at a time, so you need to walk several times. According to the recommendation, it can be optimized if, after 0.5 log(n) circles, everything is finished with insertion sort. The speed, of course, is so-so, but it looks interesting. But is it possible to squeeze even more out of it, for example, by getting rid of recursion? (And does recursion have a big impact on speed?)

public void sort(int[] array) {
    int numOfSwaps = 0;

    for (int i = (int) (0.5 * Math.log(array.length)); i >= 0; i--) {
        numOfSwaps = circleSort(array, 0, array.length - 1, 0);
    }

    if (numOfSwaps != 0) {
        for (int i = 1; i < array.length; i++) {
            int temp = array[i];
            int j = i;

            while (j > 0 && array[j - 1] > temp) {
                array[j] = array[j - 1];
                j = j - 1;
            }
            array[j] = temp;
        }
    }
}

private int circleSort(int[] array, int lowerBound, int higherBound, int numOfSwaps) {
    if (lowerBound == higherBound) return numOfSwaps;

    int low = lowerBound;
    int high = higherBound;
    int middle = (higherBound - lowerBound) / 2;

    while (lowerBound < higherBound) {
        if (array[lowerBound] > array[higherBound]) {
            int temp = array[lowerBound];
            array[lowerBound] = array[higherBound];
            array[higherBound] = temp;
            numOfSwaps++;
        }
        lowerBound++;
        higherBound--;
    }

    if (lowerBound == higherBound && array[lowerBound] > array[higherBound + 1]) {
        int temp = array[lowerBound];
        array[lowerBound] = array[higherBound + 1];
        array[higherBound + 1] = temp;
        numOfSwaps++;
    }

    numOfSwaps = circleSort(array, low, low + middle, numOfSwaps);
    numOfSwaps = circleSort(array, low + middle + 1, high, numOfSwaps);

    return numOfSwaps;
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question