First, take an integer d1 less than n as the first increment, dividing the entire record of the file into D1 groups. All records that are multiples of the DL are placed in the same group. A direct insertion sort is performed within each group, and then the second increment d2<d1 repeats the grouping and sorting above until the incremental dt=1 (DT<DT-L<;...<D2<D1) is taken, where all records are placed in the same group for direct insertion sort.
The method is essentially a grouping insertion method.
Schematic diagram:
Source
Copy Code code as follows:
Package com.zc.manythread;
/**
*
* @author Me Yes
*
*/
public class Shellsort {
public static int count = 0;
public static void Shellsort (int[] data) {
Calculate the maximum H value
int h = 1;
while (H <= data.length/3) {
H = h * 3 + 1;
}
while (H > 0) {
for (int i = h; i < data.length i + = h) {
if (Data[i] < data[i-h]) {
int tmp = Data[i];
int j = i-h;
while (J >= 0 && data[j] > tmp) {
Data[j + h] = data[j];
J-= h;
}
Data[j + h] = tmp;
print (data);
}
}
Calculate the next H value
h = (h-1)/3;
}
}
public static void print (int[] data) {
for (int i = 0; i < data.length; i++) {
System.out.print (Data[i] + "T");
}
System.out.println ();
}
public static void Main (string[] args) {
int[] data = new int[] {4, 3, 6, 2, 1, 9, 5, 8, 7};
print (data);
Shellsort (data);
print (data);
}
}
Run Result:
The shell sort is unstable and its space overhead is O (1), and the time cost is estimated between O (N3/2) ~o (N7/6)