Search code examples
javaalgorithmsortingshellsort

Sorting algorithm not displaying correct output


I don't understand why I am not getting correct output from my shell sorting algorithm, I cannot identify the problem, any help will be greatly appreciated.

public class sortingExample {
public static void main(String args[]) {
    int[] myArray = {4, 1, 3, 2, 1, 2};
    int increments = (myArray.length/2), i, tmp, j;
    for(; increments > 0; increments /= 2) {
        for(i = increments; i < myArray.length; i++) {
            j = i - increments;
            tmp = myArray[j];
            if(myArray[j] > myArray[i]) {
               myArray[j] = myArray[i];
               myArray[j] = tmp;
            }
        }
    }
    System.out.println(myArray[0]);
}

It should return the smallest number but instead no change is occurring, all the numbers remain in their corresponding positions.


Solution

  • Change you swap implementation inside if-statement. You have set the same element in your array twice with j as index.

    tmp = myArray[j];
    if(myArray[j] > myArray[i]) {
        myArray[j] = myArray[i];           
        myArray[i] = tmp; //here you have to set a tmp value for i-element to swap two values
    }