Java implementation binary Insert sort algorithm __ algorithm

Source: Internet
Author: User
Tags comparable static class
Preface

The binary insertion sort algorithm is an algorithm for sorting, which finds the insertion point in the comparison area through "binary lookup", which reduces the number of comparisons, the number of moves, and the time complexity remains
O (n^2); The algorithm describes the element of the first element as a lookup area, just beginning the lookup zone containing only ary[0] (the first element) takes out the next element (which is recycled here, starting with the second element), and compares the median of the lookup zone (the half-search method). Note: The elements in the lookup zone are sorted. If the new element is less than the intermediate element, moves the right edge of the lookup area (represented by it) to the left one bit, and if greater than or equal to the middle element, moves the left edge (represented by the left-hand variable) to the left one repeat step 3 until the left edge is greater than the right boundary Determines whether the left boundary is within the lookup area, and if it starts at the index position found, ends at the index of the comparison element and moves backward one bit. If you are outside the right boundary, ignore this step to overwrite the found element with the elements of the comparison (data removed in the second step) repeat the second step

Tip: The above from the second step to the end of the 7th step, each cycle of the comparison area inside the right side is incremented until the incremental end algorithm description diagram

The above is in the beginning to write the basic knowledge of this article, if still do not understand does not matter, I found a good link to explain, please see the following resources Why write this article

This article is not so much to record the binary sorting algorithm, but rather a summary, from the code I posted from the back I can see that I deliberately applied in the encapsulation class generics, internal classes, and provide 2 comparable and comparator implementation class calls overloaded sorting method, In the previous phase of the consolidation of the Java foundation of a test, I would also like to see this article to help people, due to their own level of relationship, if there is a wrong place, I hope to point out. Body

In the preface I described the steps and principles of the binary sorting algorithm, and I started with a code to implement the algorithm to analyze

public void Binarysort (t[] obj, comparator<t> Comparator) {//define some variables required by the binary insert algorithm int le
           FT, right, mid;
            T curvalue = null;
                 for (int start = 1; start < obj. length; start++) {Curvalue = obj[start];
                 left = 0;
                 right = Start-1;
                      The following code uses the semi-search method in the comparison area to find the position that can be inserted while (left <= right) {///using bit operations to find the middle position of the comparison area
                      Mid = (left + right) >> 1;
                            if (Comparator.compare (Curvalue, obj[mid]) < 0) {///when Curvalue is less than obj[mid], the right boundary moves left
                     Right-= 1;
                     else {//Here you need to note that if two values are equal also let the left border move one Left + + 1; }//End loop left = right + 1;
      And the left <= start//left is where the element needs to be inserted, and movestep indicates that the element between Left-start is moved back one           int movestep = Start-left; System.
                 Arraycopy (obj, left, obj, left+1, movestep);
           obj[left] = Curvalue; }
     }

From the above we can see that the code has two loops, the first for loop is corresponding to 2-7 steps, and the second while loop corresponds to 2-4 steps, we need to notice that start starts with the second element of the array, and the first element I set to look for the interval element, Right is related to this start, so that the lookup interval can be extended continuously. When the loop ends, it means I've found the insertion position, and then, through the Arraycopy function, the qualifying array is moved to the right, and then the data to be compared is used to overwrite the value on the found index.
I think it is necessary to remind that is the half-search method is for the ordered array, so the search interval according to the set, expanding after the data is also sorted well

Test Code

Package org.study.arithmetic;
Import Java.util.Arrays;
Import Java.util.Comparator;


Import Java.util.Random; public class Binarysortac<t> {/** * binary insert algorithm sort * @param outside pass an array reference that needs to be sorted/public void B
           Inarysort (t[] obj, comparator<t> Comparator) {//define some variables required for the binary insert algorithm int left, right, mid;
            T curvalue = null;
                 for (int start = 1; start < obj. length; start++) {Curvalue = obj[start];
                 left = 0;
                 right = Start-1;
                      The following code uses the semi-search method in the comparison area to find the position that can be inserted while (left <= right) {///using bit operations to find the middle position of the comparison area
                      Mid = (left + right) >> 1;
                            if (Comparator.compare (Curvalue, obj[mid]) < 0) {///when Curvalue is less than ojb[mid], the right boundary moves left
                     Right-= 1; else {//Here you need to note that if the two values are equal also let the left border move left oneBit left + 1; }//End loop left = right + 1; And the left <= start//left is where the element needs to be inserted, and movestep indicates that the element between Left-start is moved back one int movestep = STA
                Rt-left; System.
                 Arraycopy (obj, left, obj, left+1, movestep);
           obj[left] = Curvalue;
      } @SuppressWarnings ({"Unchecked", "Rawtypes"})/** * Sort overloaded methods, where I cannot use generics because generics cannot invoke the CompareTo method     
            * @param obj needs to compare data sets/public void Binarysort (object[] obj) {//define some of the variables required for binary insertion algorithm
           int left, right, mid;
            Comparable curvalue = null;
                 for (int start = 1; start < obj. length; start++) {Curvalue = (comparable) obj[start];
                 left = 0;
                 right = Start-1;
                      while (left <= right) {mid = (left + right) >> 1; if (cUrvalue.compareto (obj[mid]) < 0 {right-= 1;
                     else {left = 1; }//End loop left = right + 1; And the left <= start//left is where the element needs to be inserted, and movestep indicates that the element between Left-start is moved back one int movestep = STA
                Rt-left; System.
                 Arraycopy (obj, left, obj, left+1, movestep);
           obj[left] = Curvalue;  }} @SuppressWarnings ("Unchecked")/** * @return Returns a specific set/public user<string>[]
            GetList () {user<string>[] users = new USER[10];
                 for (int index = 0; index < index++) {user<string> User = new user<string> ();
                 User.setname ("Abigail" + index);
                 User.setage (New Random (). Nextint (100));
           users[index] = user;
     return to users;

    } /** * * * * @param <T> user use the generic parameters of the peripheral class * * private static class User<v> {
            private V name;

            private int age;
           Public v. GetName () {return name;
           public void SetName (V name) {this. name = name;
           public int getage () {return age;
           public void Setage (int age) {this. age = age;
                 Public String toString () {StringBuilder SBU = new StringBuilder ();
                        return Sbu.append ([name:]). Append (name). Append (", Age:")
           . Append (age). Append ("]"). ToString ();
            }/** * @return returns a specific comparer */public comparator<user<string>> Getcomparator () {
     return new Mycomparator (); }
     /** Internal class implements a User's comparer * @param args/Private class Mycomparator implements Comparator<user<st ring>>{@Override/** * Compare the size of two objects with age */public int com
           Pare (user<string> O1, user<string> O2) {return o1.getage ()-o2.getage (); } public static void Main (string[] args) {binarysortac<integer> ite = new BINARYSORTAC&L
           T;integer> ();
           integer[] ites = new integer[] {5,2,10,6,4,3,1,5,10}; System.
            Out.format ("Sort before%s\n", Arrays.tostring (ites));
           Ite.binarysort (ITES); System.

           Out.format ("Sorted after%s\n", Arrays.tostring (ites));
           binarysortac<user<string>> ite1 = new binarysortac<user<string>> ();
           user<string>[] users = ite1.getlist (); System.
            Out.format ("Sort before%s\n", arrays.tostring (users)); Ite1.binarysort (Users, ite.geTcomparator ()); System.

     Out.format ("Sorted after%s\n", arrays.tostring (users)); }
}
reference materials

binary Insert Sort algorithm description (left small right big)
Http://wenku.baidu.com/link?url= 16jgfpzd4kylb8rmyuliinnnwsvtcay916vgxlqpce47h3d8x96k2wjx0cnaj8urqyaq70pknhyvheaxoeyk34tskaasugkkf5zsvgizuje

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.