Java sorting Algorithm (iii): Direct Insert Sort

Source: Internet
Author: User

[Basic idea]

Key: Find the right insertion position in the sequence that is already sorted in front

Steps:

1. Starting with the first element, the element can be considered ordered.

2. Take the next element and compare it in a sequential sequence of elements from a backward-forward scan.

3. If the element (sorted) is greater than the new element, move the element to the next position.

4. Repeat step 3 until you find that the sorted element is less than or equal to the position of the new element.

5. Insert the new element after the position.

6. Repeat steps 2~5


[Java Implementation]

public class insertsort {public static void main (string[] args) {int[] arr = {6, 5, 3, 1, 8, 7, 2, 4}; System.out.println ("Before sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");} Direct Insert sort insertsort (arr); System.out.println (); System.out.println ("After sorting:"); for (int i = 0; i < arr.length; i++) {System.out.print (Arr[i] + "");}} /** * Direct insertion sort */private static void Insertsort (int[] arr) {int J;//sorted list subscript int t;//To sort elements for (int i = 1; i < Arr.lengt H  i++) {if (Arr[i] < arr[i-1]) {t = Arr[i];//Assign value to the element to be sorted for (j = i-1; J >= 0 && arr[j] > t; j--) {Arr[j + 1] = Arr[j]; Iterate through the sorted list, one by one, compared to the element to sort, and if the sorted element is large, move it backward}arr[j + 1] = t; Insert the element to be sorted into the correct position}}}} 

Reviews: It is important to set the variable T, which remembers the value of the element to be inserted, and it does not matter when the element is moved.


[Algorithmic features]

Complexity of Time: O (n^2)

Direct insert sorting is better than bubbling and simple sorting performance.

Java sorting Algorithm (iii): Direct Insert Sort

Related Article

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.