Insert sort and merge sort of algorithm introduction

Source: Internet
Author: User

As a front-line of the yards to see the algorithm and data structure is still very necessary, although the "Introduction to the algorithm" this book is difficult to chew, but it is necessary to chew. Algorithm this thing and some programming language relationship is not very small, in the University of the classroom is generally used to describe the code pseudo-coding, and the C language to achieve. The algorithm is more a kind of thought, a problem-solving method, more look at the algorithm is still very necessary, it can open up your ideas, so that you are more active in programming thinking.

Of course, I have limited level of algorithm, this is not an effort to learn is not, followed by the introduction of algorithms described in the insertion sort and merge sort using objective-c language implementation, of course, what language is secondary, the key is to understand the algorithm is the key.

First, to create our test project

Because we only understand the corresponding algorithm, there is no user graphics, there is no UI, here using Xcode to create a Mac-based console project can be, the whole project is simple, a main function of a sort class, as shown below.

In the sort class we wrote some class methods for sorting, and then called in the main function.

Second, insert sort

Insert sort as the name implies, is to insert the unordered elements into the ordered elements. The introduction to the algorithm cited an example of a specially-designed image, inserting the sort as if you were playing poker while the cards were in order, and the cards you just touched were random and needed to be inserted into the ready-to-order poker, which is the insertion sort.

If it is implemented in code, the ordered elements in the front will be added one after each round of insertions, and the subsequent unordered elements will be reduced by one. Below, according to the example of demo to illustrate the idea of inserting the sort and how to implement it concretely.

1. Because a mutable array in OC is a reference type, it does not need to be returned after a change in the function.

2. Since there is only one data in the array, it is ordered, so the initial sequence of the preceding order has a data, that is, the first data in the original array. We start with a subscript of 1 to iterate through each unordered element, inserting the element in the corresponding position in the preceding ordered element, but must ensure that the ordered array remains orderly after insertion.

3. We need to stage the data that is about to be inserted into an ordered sequence, because an ordered sequence is larger than the element that is currently inserting data that needs to be moved back to prepare for the insertion of the element. The movement of an ordered element overrides the element to be inserted, so it must be staged.

4. Iterate through the ordered sequence, find the appropriate insertion position, and insert the element.

1+(void) Insertionsortwitharray: (Nsmutablearray *) array{2     3     //Insert from the second number to the previous data, and each pass through the outer loop, insert a value from the back ,4     //thus, without a round of outer loops, the length of the ordered sequence increases by one5      for(inti =1; i < Array.count; i + +) {6         7         //staging the data that will be inserted into the front8NSNumber *key =Array[i];9         Ten         //gets the subscript of the last element of an ordered sequence One         intj = i-1; A          -         //Loop through the ordered sequence to find the appropriate data insertion position, in this process, for the insertion of data to make a position, that is, the -         //move backward with elements larger than the data that will be staged the          while(J >=0&& Array[j] >key) { -              -array[j+1] =Array[j]; -              +j--; -         } +          A         //Inserting Data atarray[j+1] =key; -          -NSLog (@"The results of the first round insert sorting are as follows:", i); - [self displayarraywitharray:array]; -  -     } in}

Displayarraywitharray is the method of writing the data in the output array in advance, the code is as follows, the method is to stitch the array elements into a string, and then output.

1+(void) Displayarraywitharray: (Nsmutablearray *) array{2     3nsmutablestring *strtemp = [nsmutablestringstring];4      for(inti =0; i < Array.count; i++) {5[strtemp AppendFormat:@"%@, ", Array[i]];6     }7NSLog (@"%@\n\n", strtemp);8}

Next, let's use the random number in the main function to produce a random array and then test it as follows:

1         // Generating a test random array 2         Nsmutablearray *array = [[Nsmutablearray alloc] init]; 3         Ten ; 4          for (int0; i < count; i + +) {5             NSNumber *temp =  @ (arc4random ()%); 6             [Array addobject:temp]; 7         }

Enter the test phase, call the Displayarraywitharray method, print the original array randomly generated, and then call the insert sort as follows:

1         NSLog (@ " original array as follows:"); 2         [Sort Displayarraywitharray:array]; 3         4         // Insert Sort 5         [Sort Insertionsortwitharray:array];

Input results are as follows, sorted as follows, at a glance, the first round is the front two ordered, the second round is the front 3 ordered, and so on, the complexity of the algorithm is O (n2)

Three, merging algorithm

Merging algorithm is because the original problem is decomposed into smaller sub-problems, and then the sub-problem is more simple than the original problem, the solution of the problem is effectively merged, and then get the whole problem solution. This is the idea of divide and conquer.

Next, we will implement the merge sorting algorithm.

1. First implement the merge part of the code, to merge the array is already sorted out, the following is the code to merge the array, as follows:

1 //One merge2+(void) Mergewitharray: (Nsmutablearray *) Array3 Withstarindex: (nsinteger) Starindex4 Withmidindex: (nsinteger) Midindex5 Withendindex: (nsinteger) EndIndex6 {7     //record merge times8     Static intSort_count =0;9     Ten     if(EndIndex <Starindex) { One         return; A     } -      -     //number of elements in the first half theNsinteger Frontcount = Midindex-starindex +1; -      -     //number of elements in the second part -Nsinteger Rearcount = EndIndex-Midindex; +      -     //split the array into two parts to merge +      A     //remove the first half of the section atNsmutablearray *frontarray =[[Nsmutablearray alloc] initwithcapacity:frontcount]; -      for(Nsinteger i =0; i < Frontcount; i + +) { -[Frontarray Addobject:array[starindex +i]]; -     } -      -     //Remove the latter half of the part inNsmutablearray *reararray =[[Nsmutablearray alloc] initwithcapacity:rearcount]; -      for(Nsinteger i =0; i < Rearcount; i + +) { to[Reararray Addobject:array[midindex + i +1]]; +     } -      the      *     //to compare and merge $     Panax NotoginsengNsinteger fi =0; -Nsinteger ri =0; theNsinteger Oi =Starindex; +      A     //merge when there are elements in two sub-arrays the      while(Fi < Frontarray.count && Ri <reararray.count) { +          -         if(Frontarray[fi] <=Reararray[ri]) { $              $array[oi++] = frontarray[fi++]; -             Continue; -         } the          -array[oi++] = reararray[ri++];Wuyi     } the  -     //after merging the elements in the preceding elements, the remaining elements are added Wu      while(Fi <frontarray.count) { -          Aboutarray[oi++] = frontarray[fi++]; $          -     } -  -     //after the elements have been merged, there are still elements to add the remaining elements. A      while(Ri <reararray.count) { +          thearray[oi++] = reararray[ri++]; -          $     } the      theNSLog (@"The results of the merger of%d are as follows:", ++sort_count); the [self displayarraywitharray:array]; the}

The above code is just a merger of the problem solution, below is to split the problem, decomposition into smaller size sub-problem, recursive decomposition code is as follows, in this is not much to say, the following code has given a comment.

1 #pragmaMark-This method is to recursively divide the problem into several similar sub-problems, and then in the problem of2+(void) Mergesortwitharray: (Nsmutablearray *) Array3 Withstarindex: (nsinteger) Starindex4 Withendindex: (nsinteger) EndIndex5 {6     //Recursive End Condition7     if(Starindex >=EndIndex) {8         return;9     }Ten      One     //find the midpoint to decompose ANsinteger Midindex = (starindex + endIndex)/2; -      -     //recursive decomposition of the first half part the [self Mergesortwitharray:array withstarindex:starindex withendindex:midindex]; -      -     //recursive decomposition of the latter half part -[Self Mergesortwitharray:array Withstarindex:midindex +1Withendindex:endindex]; +      -     //after the recursive decomposition above, there is only one element in the smallest sub-array, which is ordered, then recursively merges from the bottom + [self Mergewitharray:array withstarindex:starindex withmidindex:midindex Withendindex:endindex]; A      at}

  

Call the merge sort code as follows:

1         // Merge Sort 2         [Sort mergesortwitharray:array Withstarindex:0 withendindex:array.count-1];

The results of the operation are as follows, carefully observing the results after each merge, you will find the regular OH.

Today's blog is first here, programming is the algorithm Ah, continue to study.

Insert sort and merge sort of algorithm introduction

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.