C/c ++ common algorithms (11) -- Basic sorting algorithms (insert sorting)

Source: Internet
Author: User

Insert sort


It is based on the "bridge players" approach. That is, before observing the record Ri, set all previous records R1, R2 ,...., The Ri-1 is sorted, and Ri is inserted to the appropriate location of the sorted records.

The most basic insert sorting is the direct insert sorting (Straight Insertion Sort ).


1. Insert sorting directly


1.1 sorting Ideology

Insert the record Ri to the sorted record table R1, R2 ,...., In the Ri-1, a new ordered table with 1 more records is obtained. Until all records are inserted.

The order of records to be sorted is stored in the array R [1... N], at a certain time point of sorting, the record sequence is divided into two parts:

◆ R [1... I-1]: ordered part;

◆ R [I... N]: unordered parts.

Obviously, at the beginning of sorting, R [1] is sorted.


1.2 example




1.3 implementation code:

# Include
 
  
# Include
  
   
# Define SIZE 10 void InsertionSort (int * a, int len) {int I, j, t, h; for (I = 0; I
   
    
= 0 & t
    
Running result:




2. Hill sorting


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + export/XQodT2wb + export + PGJyPgo8L3A + export/export + CjwvcD4KPHA + pgltzybzbzcm9 "http://www.bkjia.com/uploadfile/Collfiles/20140105/20140105094550149.jpg" alt = "\">


2.3 Implementation Code:

# Include
     
      
# Include
      
       
# Define SIZE 10 void ShellSort (int * a, int len) {int I, j, h; int r, temp; int x = 0; for (r = len/2; r> = 1; r/= 2) {for (I = r; I
       
        
= 0 & temp <a [j]) {a [j + r] = a [j]; j-= r;} a [j + r] = temp ;} x ++; printf ("% d walking Result:", x); for (h = 0; h <len; h ++) {printf ("% d", a [h]);} printf ("\ n") ;}} int main (int argc, const char * argv []) {int shuzu [SIZE], I; srand (time (NULL); for (I = 0; I
        
         
Running result:




Reference books: C/C ++ common algorithm manuals, data structures-yan Weimin, Tsinghua University

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.