Shell sort
Shell sort is based on the Insertion sorting algorithm, and it belongs to the group of very efficient algorithms. In general, the algorithm breaks an original set into smaller subsets and then each of those is sorted using Insertion sort.
But, how it makes the subsets is not straightforward. It doesn’t choose neighboring elements to form a subset as we might expect. Rather, shell sort uses the so-called interval or gap for subset creation. For example, if we have the gap I, it means that one subset will contain the elements that are I positions apart.
Firstly, the algorithm sorts the elements that are far away from each other. Then, the gap becomes smaller and closer elements are compared. This way, some elements that aren’t in a correct position can be positioned faster than if we made the subsets out of the neighboring elements.
codes
public class Study {
/**
* main function to sort array using shell sort
*
* @param args
*/
public static void main(String[] args) {
int[] arr = {1, -10, -2, 3, 8, 100, -100, 2, 6, 25};
print(arr);
System.out.println();
shellAsc(arr);
// shellDes(arr);
print(arr);
}
/**
* ascending order
*
* @param arr
*/
private static void shellAsc(int[] arr) {
/*
gap means the gap between each sub_array, the original gap is set to be arr.length / 2
thus there will be arr.length / 2 groups, and we will decrease the gap by half and group
number will decrease accordingly by half
*/
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
// insertion sort from index gap to the end of arr.length - 1
// this inner for loop is definitely insertion sort with gap interval
for (int i = gap; i < arr.length; i++) {
int newElement = arr[i];
int j = i;
while (j >= gap && arr[j - gap] > newElement) {
arr[j] = arr[j - gap];
j -= gap;
}
arr[j] = newElement;
}
}
}
/**
* descending order
*
* @param arr
*/
private static void shellDes(int[] arr) {
for (int gap = arr.length / 2; gap > 0; gap /= 2) {
for (int i = gap; i < arr.length; i++) {
int newElement = arr[i];
int j = i;
while (j >= gap && arr[j - gap] < newElement) {
arr[j] = arr[j - gap];
j -= gap;
}
arr[j] = newElement;
}
}
}
/**
* swap values
*
* @param arr
* @param i
* @param j
*/
private static void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/**
* print the array
*
* @param arr
*/
private static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print("arr[" + i + "] = " + arr[i] + " ");
}
}
}
Result
arr[0] = 1 arr[1] = -10 arr[2] = -2 arr[3] = 3 arr[4] = 8 arr[5] = 100 arr[6] = -100 arr[7] = 2 arr[8] = 6 arr[9] = 25
arr[0] = -100 arr[1] = -10 arr[2] = -2 arr[3] = 1 arr[4] = 2 arr[5] = 3 arr[6] = 6 arr[7] = 8 arr[8] = 25 arr[9] = 100