Shell Sort Example Java Program

Definition

Shellsort, also known as Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange or sorting by insertion. The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared.

Shell Sort Example Program

class ShellSort {
    public static void main(String args[]) {
        int[] arr = new int[] { 300, 200, 500, 400, 100 };
		System.out.println("Array before sorting is ");
		for(int i=0;i 0; inc /= 2){
		for (int i = inc; i < arr.length; i++){
			k = arr[i];
			for (j = i; j >= inc; j -= inc) {
				if (k < arr[j - inc]) {
					arr[j] = arr[j - inc];
				} else {
					break;
				}
			}
			arr[j] = k;
		}
	}
	System.out.println("After Sorting is ");
	for (int i = 0; i < 5; i++) {
		System.out.println(arr[i]);
	}
    }
}

Sample Output

Output is:
Array before sorting is
300
200
500
400
100
After Sorting is
100
200
300
400
500