Sort-InsertionSort insert sort, sort-insertionsort

Source: Internet
Author: User

Sort-InsertionSort insert sort, sort-insertionsort

Insert sort implementation

Insert sorting is like a bet, such as a double button. When you draw a card, take one card at a time. This card is compared with the previous card. Select the position where the card is inserted, and sort the order to make the cards smoother. Otherwise, it may be difficult to find them one by one. It is not conducive to playing cards. View

Assume that plum blossom 7 is drawn for the first time without sorting. Because there is only one

Then draw plum blossom 10. Because 10 is bigger than 7, no sorting is required.

And then draw the cards. Found that the plum blossom 5. Don't hesitate at this time. is really not big. Discard card decisively

Then we compare the values of 5 and 10. 5 is less than 10, so the switching position.

Compare 5 to 7. 5 is smaller than 7. Therefore, you can obtain the values at the locations of 5 and 7.

This is already sorted. This is how it works.

Because it is relatively simple. Directly paste the code

  

// O (n ^ 2) Worst Case // best case O (n) public static void sort (Comparable [] a) {for (int I = 1; I <. length; I ++) {for (int j = I; j> 0; j --) {if (less (a [j], a [j-1]) exch (a, j, j-1); else break ;}} public static void sort (Comparable [] a, int low, int hi) {for (int I = low; I <= hi; I ++) {for (int j = I; j> low; j --) {if (less (a [j], a [j-1]) exch (a, j, j-1); else break ;}}}
InsertSort

Complete code in https://github.com/Cheemion/algorithms/blob/master/src/com/algorithms/sort/InsertionSort.java

Performance Analysis

The worst case is that every time the card is drawn, it is the smallest. At this time, you need to traverse from the tail to the header each time. Time is proportional to N ^ 2

The best case is that the order has been sorted. Because the order has been sorted. Therefore, the Cards drawn each time do not need to be sorted. Time is proportional to N

 

 

 

  

 

  

 

  

 

 

  

  

  

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.