Question

I've been debugging this piece of code for a while now and I simply can't figure out why it doesn't work. It's an attempt at implementing a sequential insertion sort in Java.

public void resultSort(int[] resultSet){
    int j;
    for(int i = 0; i < resultSet.length; i++){
        j = i;
        while(j > 0 && resultSet[j-1] < resultSet[j]){
            swap(j, j-1);
            j = j-1;
        }
    }
}

public void swap(int index1, int index2){
    int sw = numbers[index1];
    numbers[index1] = numbers[index2];
    numbers[index2] = sw;
}

If somebody could point out the error here, I'd be very happy. Thanks in advance!

Was it helpful?

Solution

You seem to have an issue with numbers vs resultSet. If you pass your numbers array as a parameter to your sorting function, it can work.

Some advice:

  • pass on your resultSet as parameter to your swap function so as to maintain consistency on which array you're actually sorting
  • refrain from using class-scoped arrays for that kind of operations (this one is arguable and depends on your actual task)

OTHER TIPS

If you call resultSort(numbers) it works. Your algorithm sorts descending. Here is my testcode I did some small changes to make it all static. I guess the problem is, that resultSort is not called with parameter numbers.

    static int numbers[] = new int[]{34, 24, 56, 12, 45, 2, 53, 758};

    public static void main(String[] args) {
        resultSort(numbers);
        for (int i : numbers) {
            System.out.println(i + " ");
        }
    }

    public static void resultSort(int[] resultSet) {
        int j;
        for (int i = 0; i < resultSet.length; i++) {
            j = i;
            while (j > 0 && resultSet[j - 1] < resultSet[j]) {
                swap(j, j - 1);
                j = j - 1;
            }
        }
    }

    public static void swap(int index1, int index2) {
        int sw = numbers[index1];
        numbers[index1] = numbers[index2];
        numbers[index2] = sw;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top