Sorting of data structures and algorithms one: merge sort

Source: Internet
Author: User

We have to admit the fact that in the course of Java Learning we can do some development if we have mastered a variety of programming methods and tools, which is why some training institutions dare to tell you that you can master a language in a few months. But with the development of time, we always feel that this kind of people if not to promote themselves, and finally will only be a yard farm. Technology will change rapidly, at any time in the development of the replacement, but these decades, who said the algorithm will be outdated, if we say that the Java language engine is a variety of development tools and technology, then we can not be polite to say that the algorithm will be his soul. A programmer's ascension and overstating must be lofty high-rise ground, then I hope this foundation is a data structure and algorithms, master these principles in the future in the course of learning we will be unusually easy.

First, we need to master several basic sorting methods, such as simple sort, insert sort, quick sort, heap sort, bubble sort, select Sort, hill sort, merge sort. Each sort has its own characteristics, the size of the data or the complexity of the time, the requirements of space complexity can choose the appropriate sorting method to sort. As far as I am concerned, because I am in the process of learning to merge the sort of love, so today we introduce the merge sort. We will demonstrate the Java implementation Code of the merge sort, as well as the characteristics of the merge, its time complexity and space, and so on.

One: The characteristics of merge sort:

The characteristics of merge sort 1th is that it is a more representative of the divide and conquer thought of the sort, which permeates the idea of recursion, when we face a lot of complex complex data to do not know, perhaps divide and conquer is our first choice, this determines the merge sort is best in the data volume is larger, The space complexity requirements are not high, the time is complex with a certain demand for the use of the case. Because it takes up the stack space in the process of constantly splitting data recursively. Speaking of which may be a bit confusing, then we directly on the code to see how to achieve the merge sort.

Two: Code implementation:

The first step: we call it merging, then inevitably involves the merger, if there is a merger, then there must be a corresponding split. In this step we correspond to the sort method, which allows a complete array to be continuously split until the last data unit is a separate data location, at which point the second step is to continuously integrate the separate data from small to upper.

Step Two: We see the Mergearray () method, which is the most temporary container of a temporary array, storing the sorted array after the comparison, and then fetching the assigned value to the original data. Here are a few more points to understand,

1th: We are merging the data sets on both sides of the middle data, by comparing, let the small into the temporary array, the corner label plus one, in the comparison, until a data set to the end of the position.

2nd: We will have a data set after the comparison will leave some data is not inserted, this time we compare their start and end of the corner, if not equal then the data in this collection of data continue to join our temporary array through the while loop.

3rd: At the end of the day, we put the data in the temporary array into the original array, we must remember to add the value of start, because we all know that at the time of merging, we are at the same time, the left side of the data may be starting from 0, but the data on the right is not necessarily, so we have to add the merger Starting position start.

4th: Must pay attention to a thing, algorithm to understand very difficult, but we may need to practice, in the logical processing of the operation is not understood, can be on the draft paper process decomposition, or through the source code debag mode, analyze the trend of the data.

1  Public Static voidSortintArr[],intEmp[],intStartintend) {2        //judge whether to continue splitting recursion3          intMiddle = start + (End-start)/2;4          if(Start <end) {5Sort (arr,emp,start,middle);//split the data on the left and make it orderly6Sort (arr,emp,middle + 1,ens);//split the data on the right and make it orderly7Mergearray (Arr,emp,start,middle,end);//to merge8          }9 }Ten  Public Static voidMergearray (intArr[],intEmp[],intStartintMiddle,intend) { One          inti = Start,j =Middle; A          intK = middle + 1,z =end; -          intx = 0; -          //judge that data size insert temporary array the           while(I <= j&& k <=z) { -               if(Arr[i] <Arr[k]) { -emp[x++] = arr[i++];  -}Else{ +emp[x++] = arr[k++]; -                } +           } A         //when we split both sides of the data into a temporary array, there must be unfinished data in the original array . at         //continue with Data cleanup, join temporary array -          while(I <=j) { -emp[x++] = arr[i++]; -        } -          while(k <=z) { -emp[x++] = arr[k++]; in        } -         //after all the data goes into the temporary array, we export the data into the original array, which must be orderly to         for(i = 0;i < x;i++){ +Arr[start + i] =Emp[i]; -        } the  *}

Three: Algorithm process analysis diagram:

          

Four: Merging time complexity calculation and analysis: For this piece we may try to understand, for all aspects of the comprehensive consideration for beginners may be more difficult.

It can be said that the combination of sorting is a more complex sort, especially for students who do not understand the basic idea of the division method may be difficult to understand. Total time = decomposition time + solve problem time + merge time.

Decomposition time: Decomposition of a sequence to be sorted into two sequences, time is a constant, time complexity O (1).

Solve the problem time: Two recursive, the problem of a scale n is divided into two sub-scale N/2, the time is 2T (N/2). The merge time complexity is O (n).

Total time: T (n) =2t (N/2) +o (n). This recursion can be solved with a recursive tree, and its solution is O (NLOGN). In addition, in the worst, best, and average cases, the merge sort time complexity is O (NLOGN). You can see that the consolidation sort is stable from the merging process.

Recursive tree method for recursive t (n) =2t (N/2) +o (n): Assuming that the last sub-problem is fixed to a constant C, the overall problem size is CN for n Sorted records.

           

From this recursive tree can be seen, the first layer of time cost is CN, the second layer of time cost is CN/2+CN/2=CN .... Each layer cost is CN, a total of logn+1 layer. So the total time cost is cn* (logn+1). Time complexity is O (NLOGN)

Sorting of data structures and algorithms one: merge 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.