Sorting algorithm merge sort and its time complexity and space complexity

Sorting algorithm merge sort and its time complexity and space complexity

The efficiency of quick sort in the sorting algorithm is very high, but there is another sorting algorithm that can be comparable in efficiency, that is merge sort; merge sort and quick sort have the same effect. The magic, quick sort: first roughly sort the array into two sub-arrays, and then roughly divide the two sub-arrays recursively, until there is only one element in the sub-array, then it will be sorted naturally, which can be summarized as sorting first and then recursive ; Merge sort: No matter what, divide the array into two sub-arrays, and divide the array into two sub-arrays recursively until there is only one element in the array, then sorting starts, so that the two arrays are sorted in sequence, Sort the two arrays according to the recursive return, and sort the entire array at the end;


Analysis of Algorithms

        Merge sortIt is an effective sorting algorithm based on the merge operation, This algorithm is a very typical application of Divide and Conquer. Combine existing ordered subsequences to obtain a completely ordered sequence; that is, first make each subsequence in order, and then make the subsequences in order. If you merge two ordered lists into one ordered list, Called two-way merge
The basic idea:
        First divide the array into two sub-arrays recursively, until there is only one element in the array, and then call the function to sort the two sub-arrays, because this function will be pushed onto the stack when recursively dividing the array, so this function really The role of is to sort two ordered sub-arrays;
The basic steps:
        1. Judge the validity of the parameters, that is, the recursive exit;
2. No matter what, first divide the array into two sub-arrays;
3. The function of dividing the array is called recursively, and finally there is only one element in the array, which also means that the array is ordered;
4. Then call the sorting function to merge the two ordered arrays into one ordered array;
5. The steps of the sorting function, compare the elements of the two arrays, store the larger/smaller elements in a temporary array, if one of the elements of the array is taken out, then directly put the elements of the other array To the temporary array, and then copy the elements in the temporary array to the actual array;

Implementation code

#include<stdio.h>  
   
 #define LEN 12 // Macro defines the size of the array  
   static int tmp[LEN] = {0};// Set temporary array  
   
 // print array  
 void print_array(int *array)  
 {  
     int index = 0;  
     printf("\narray:\n");  
     for (; index < LEN; index++){  
         printf(" %d, ", *(array + index));  
     }  
     printf("\n");  
 }  
   
 // Sort two ordered arrays into one array  
 void _mergeSort(int *array, int start, int middle, int end)  
 {  
    int first = start;  
    int second = middle + 1;  
    int index = start;  
    while ((first <= middle) && (second <= end)){  
        if (array[first] >= array[second])  
            tmp[index++] = array[second++];  
        else  
            tmp[index++] = array[first++];  
    }     
    while(first <= middle) tmp[index++] = array[first++];  
    while(second <= end) tmp[index++] = array[second++];  
   
    for (first = start; first <= end; first++)  
        array[first] = tmp[first];  
 }  
  
 // Recursively divide the array  
 void mergeSort(int *array, int start, int end)  
 {  
     if (start >= end)  
         return;  
     int middle = ((end + start) >> 1);  
           mergeSort(array, start, middle);// Recursively divide the left array  
           mergeSort(array, middle+1, end);// Recursively divide the array on the right  
           _mergeSort(array, start, middle, end);// Combine two ordered arrays into an ordered array  
 }  
   
 int main(void)  
 {  
     int array[LEN] = {2, 1, 4, 0, 12, 520, 2, 9, 5, 3, 13, 14};  
     print_array(array);  
     mergeSort(array, 0, LEN-1);  
     print_array(array);  
     return 0;  
 }  

  
 
    
Analyze the above code: In fact, the above code mainly consists of two functions, the first is the function of dividing the array, and the second is the merging function of merging two ordered arrays; here we need to use a temporary array, some people are in Apply for a dynamic array in the main function, and then let all recursive calls use the array; some people apply for a temporary array in the merge function; and my method is to define a global temporary array; in fact, I feel that these methods are all The same is the same, because whether it is a dynamic array or a global static array, a copy of data will be saved when the sort function is called by recursive release; if a temporary array is defined in the sort function, it should be the same as the previous method, because it is a local temporary array , Stored in the stack space, when the function is called, it will be released immediately. So I personally feel that these three methods are similar (if it is a temporary array defined in the merge function, all need to be pushed onto the stack; while the others only need to be pushed into the space occupied by useful data)

Run result:
 

time complexity

Time complexity analysis of merging: Mainly consider the time cost of the two functions. First, the array division functionmergeSort(); Two, ordered array merge function_mergeSort();
        The time complexity of the _mergeSort() function is O(n), because there are two loops of length n (non-nested) in the code, so the time complexity is O(n);
Simply analyze the time T[n] consumed by the merge sort with element length n: call the mergeSort() function to divide the two parts, then the time spent sorting each small part is T[n/2], and finally To merge the two parts of the ordered array into an ordered array, the time it takes for the _mergeSort() function to be O(n);

        Formula: T[n] = 2T[n/2] + O(n);
        
The formula is not derived carefully, you can refer to the following:Quick sorting of sorting algorithm and its time complexity and space complexityThe derivation of time complexity inside;

        So the result is: T[n] = O( nlogn)

        Because these steps are required no matter what the element is in, the time spent is constant, so the optimal time complexity, worst time complexity and average time complexity of the algorithm are the same as: O ( nlogn );Someone seems to say that the worst time complexity is not O(nlogn), I don’t know how to figure it out, please let me know if you know it, thank you;
 

Space complexity

        The space complexity of merge is the space occupied by the temporary array and the data pushed onto the stack during recursion: n + logn; so the space complexity is: O(n)

Trade time for space

I see that many blogs on the Internet share the merge sort method with only O(1) space complexity; because the space consumed by the traditional merge sort is mainly in the merge function (combining two ordered functions into one ordered function) , So if you want to make the time complexity O(1), then you can only make a fuss in the merge function. The code is not listed,The main idea is to rely on quick sort (in fact, it is equivalent to the merge function is replaced by the quick sort function); although this method can reduce memory consumption, but it will bring loss in time, because this time complexity has changed It became O(n^2);So this method is not an idea that has the best of both worlds;

to sum up

Although merge sort is relatively stable, it is also very effective in terms of time (the worst time complexity and the best time complexity are both O(nlogn)), but this algorithm consumes space, and generally speaking, internal sorting will not be used This method, but use quick sort; external sort will only consider the use of this method;
     
For reprinting, please indicate the author and source of the original text, and the original address:
If there is something incorrect, I hope you can correct me and learn together! Thank you! ! !

Intelligent Recommendation

Simple insertion sort algorithm and its time and space complexity

When the sorting of the records in the sequence to be sorted is in increasing order (that is, the orderly records from small to large, called positive order), reachThe smallest number of comparisons: ...

Heap sort and its time-space complexity analysis

    /* * Heap sort * A function to build a heap, a function to sort * heap initially builds a heap (large root heap), obtains the largest node among left and right children, and exchang...

Sorting algorithm merge sorting and time complexity analysis

Bubble sorting and performance optimization of sorting algorithm (time complexity + space complexity analysis) Sorting algorithm simple selection sorting and time complexity analysis Sorting algorithm...

Sorting algorithm-time complexity (average time, worst case), space complexity

1. Time complexity: under normal circumstances, in the algorithmBasic operationThe number of repeated executions is a function f(n) of the problem size n, and the time measure of the algorithm is writ...

More Recommendation

Time complexity and space complexity of the algorithm

Time Complexity time complexity The first thing to say is that the calculation of time complexity isIt is not the time when the program is run, but the number of times the algorithm executes the state...

Time and space complexity of the algorithm complexity

What is an algorithm?       ——In order to solve a certain problem and prescribed finite series of operations。 Five characteristics of the algorithm   &nb...

"Algorithm" time complexity and space complexity

Efficiency of the algorithm is divided into two: the first is time efficiency, the second is space efficiency. Time efficiency called time complexity; referred to as spatial complexity of the space ef...

The algorithm ----- time complexity and space complexity

Usually used less, often forgotten, the concept of time complexity is recorded here Complexity is a method of marking algorithms. Represented by O, usually read as big O O contains time complexity and...

Algorithm time complexity and space complexity

1. Time frequency Time frequency is the time it takes for an algorithm to execute. It cannot be calculated theoretically, and it can only be known by running tests on the computer. But it is impossibl...

Copyright  DMCA © 2018-2026 - All Rights Reserved - www.programmersought.com  User Notice

Top