Insert Sort (Java)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.