Search code examples
javasortingbubble-sortgaps-in-data

Bubble Sort to gap sort modification


I've run in to a problem and need your guidance. Basically i managed to create this Bubble Sort method. How can i modify this to Gap Sort, that rather than comparing neighboring elements each time through the list, compares elements that are some number(i) positions apart, where (i) is an integer less than n. For example, the first element would be compared to the (i + 1) element, 2nd element to the (i + 2) element, nth element to the (n-i) element, etc. A single iteration is completed when all of the elements that can be compared, have been compared. On the next iteration, i is reduced by some number greater than 1 and the process continues until i is less than 1

public static void bubbleSort (Comparable[] data, int maxlength){
    int position, scan;
    Comparable temp;

    for (position = maxlength; position >= 1; position--){
        for (scan = 0; scan <= position – 1; scan++){
            if (data[scan].compareTo(data[scan+1]) > 0){
                // Swap the values
                temp = data[scan];
                data[scan] = data[scan + 1];
                data[scan + 1] = temp;
            }
        }
    }
}

Solution

  • This code (found on http://www.daniweb.com/software-development/java/threads/238791/gap-sort) might help you:

    public static void gapSort (Comparable [] data, int size) {  
        int index;
        int gap, top;
        Comparable temp;
        boolean exchanged;
    
        double SF = 1.3;
        gap = size;
    
        do {
            exchanged = false;
            gap = (int) (gap / SF);
            if (gap == 0){
                gap = 1;
            }
            for (index = 1; index <= size - gap; index++) {
                if (data [index].compareTo(data [index + gap]) > 0) {
                    temp = data [index];
                    data [index] = data [index + gap];
                    data [index + gap] = temp;
                    exchanged = true;
                }
            }
        } while (exchanged || gap > 1);
    }
    

    Remember that the easiest way to sort an array of objects that implement the Comparable interface is usually Arrays.Sort()