Java Sorting Algorithm (7): semi-insertion sorting, and java semi-insertion sorting

Source: Internet
Author: User

Java Sorting Algorithm (7): semi-insertion sorting, and java semi-insertion sorting

Java Sorting Algorithm (7): semi-insertion sorting

  The half insert sorting method is also called the binary insert sorting method, which is an improved version of the direct insert sorting method, and also needs to execute the I-1 insertion. The difference lies in the I-th insertion. First, find the position where the I + 1 element should be inserted. Assume that the first data is already in order.

  Code Implementation

  

Package com. spring. test;/*** semi-insertion sorting */public class BinaryInsertSort {public static void main (String [] args) {int [] data = new int [] {5, 3, 6, 2, 1, 9, 4, 8, 7}; print (data); binaryInsertSort (data); print (data );} /*** semi-insert * @ param data */public static void binaryInsertSort (int [] data) {for (int I = 1; I <data. length; I ++) {if (data [I] <data [I-1]) {// The element value at cache I int tmp = data [I]; // record the left boundary of the search Range int low = 0; int high = I-1; while (low <= high) {// record the intermediate position int mid = (low + high) /2; // compare the data size of the intermediate position and I to narrow the search scope. if (data [mid] <tmp) {low = mid + 1 ;} else {high = mid-1 ;}/// move the data at low --- I to one position for (int j = I; j> low; j --) {data [j] = data [J-1];} data [low] = tmp; print (data );}}} /*** exchange two data * @ param I * @ param j */public static void swap (int [] data, int I, int j) {if (I = j) {return;} data [I] = data [I] + data [j]; data [j] = data [I]-data [j]; data [I] = data [I]-data [j];} /*** print and output the array * @ param data */public static void print (int [] data) {for (int I = 0; I <data. length; I ++) {System. out. print (data [I] + "\ t");} System. out. println ();}}

Running result

 

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.