Package insert_sort;
Import Java.util.Random;
/* Various insertion sort
*------Data Storage Range 1~s.length-1-------
* Mainly include
* Direct Insert Sort
* Binary Insert Sort
* Hill Sort
* The following is a code implementation where the binary lookup function is used for binary insert sort
*/
public class Sort {
/*
* Binary Search
*/
private static int Binaryserach (int s[], int t, int left, int. right) {
int mid = 0;
while (left <= right) {
Mid = (left + right)/2;
if (T > S[mid])
left = mid + 1;
if (T < S[mid])
right = Mid-1;
if (t = = S[mid])
left = mid + 1;
}
return left;
}
/*
* Direct Insert Sort Stable
*/
private static void Insertsort (int s[]) {//1~s.length-1
int I, J;
for (i = 2; i < s.length; i++) {
int temp = S[i];
for (j = i-1; J > 0 && s[j] > temp; j--)
S[j + 1] = S[j];
S[j + 1] = temp;
}
}
/*
* Binary Insert Sort stable
*/
private static void Binaryinsertsort (int s[]) {//1~s.length-1
int I, j, Flag;
for (i = 2; i < s.length; i++) {
int temp = S[i];
if (temp < s[i-1]) {//found in reverse order, go to an ordered queue for binary lookup until the inserted location is found
Flag = Binaryserach (S, temp, 1, i-1);
for (j = i-1; J >= Flag; j--) {
S[j + 1] = S[j];
}
S[flag] = temp;
}
}
}
/*
* Hill sort not stable
*/
private static void Shellsort (int s[], int dk) {
int I, j, temp;
for (i = DK + 1; i < s.length; i++) {
temp = S[i];
for (j = i-dk; J > 0 && s[j] > temp; j = j-dk) {
S[j + DK] = S[j];
}
S[j + DK] = temp;
}
}
public static void Main (string[] args) {
int length = 10;
Int[] s = new Int[length];
for (int i = 1; i < s.length; i++)
S[i] = new Random (). Nextint (40);
Binaryinsertsort (s);
Insertsort (s);
Shellsort (S, 1);
for (int i = 1; i < s.length; i++)
System.out.println (S[i]);
}
}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Insert Sort (Java)