Java Insert Sort

Source: Internet
Author: User

First, the rules of inserting sorting

1. Starting from 1 increments of 1

2. Need to record the data being sorted

3. Record where the sorted data should be inserted

4. The preceding data (sorted) is moved backward, as long as it is larger than the sorted data, until it is larger or equal to stop comparing (the position of the stop subscript is the position of the sorted data).

5. Insert the sorted data into the corresponding location


Second, the code example

public class Insertsort

{

public static void Main (string[] args)

{


long[] Testarr = new long[]{111, 3, 5, 3456, 33, 2, 899, 1, 5};

Long Templong; Sorted Data Temp Variable

int tempint; Temporary variable for insertion position

for (int i = 1; i < testarr.length;i++)

{

Templong = Testarr[i]; Back up the sorted data

Tempint = i; Record the sorted data location

The preceding data (sorted) is moved backward, as long as it is larger than the sorted data, until it is larger or equal to the stop//stop comparison (the position of the stop subscript is the position of the sorted data).

while (Tempint > 0 && testarr[tempint-1] > Templong)

{

Testarr[tempint] = testarr[tempint-1];

--tempint; Move data position forward

}

Testarr[tempint] = Templong;

}

Print sorted data

for (int i = 1; i < testarr.length;i++)

System.out.println (Testarr[i]);

}

}


Java Insert Sort

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.