Get the App
SLTechnology News&Howtos  ›  Network Security  › 

C language merge sorting (merger sorting) algorithm and code

Shulou Source: shulou.com Published: 2022-06-01 07:12:39 10月25日 Update

Merge sort is also called merger sort. The algorithm idea is to divide the sequence to be sorted into two parts, then apply merge sort to the two parts in sequence, and then stop the merger. It would be very general to understand the merge sorting only from the algorithmic idea, and then use the sequence A [0], A [l]. A [n-1] stops the ascending order display to stop the explanation, and here takes a top-down approach, with the following steps.

(1) divide the sorting sequence you want to stop into two parts. If the starting element of the sequence to stop sorting is subscript first, and the subscript of the first element is last, then the critical subscript mid= (first+last) / 2 between the two parts of you is A [first... Mid] and A [mid + 1 … Last] .

(2) the two local sequences divided below are continuously divided according to the step (1) until the length of the interval is 1.

(3) stop merging and sorting the divided sequences, and the sorting method is to stop merging n sub-sequences, lose n-bank 2 or n-bank 2 subsequences containing two elements, and then stop merging the lost sub-sequences until an ordered sequence of length n is lost. Let's go through a piece of code to see how to complete the merge sort.

# include # include # define N 7 void merge (int arr [], int low, int mid, int high) {int I, k; int * tmp = (int *) malloc ((high-low+1) * sizeof (int)); / / request space with the size of two int left_low = low; int left_high = mid; int right_low = mid + 1; int right_high = high; for (kryp0; left_low)

Tags: Sort sequence element array two local ordered next subscript algorithm method single consequence pace process length you code primitive general Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL vpn NVidia MariaDB macOS