Common sorting algorithm - merge sort

1: The main idea

   Merge several ordered sequences step by step, and finally synthesize an ordered queue

Two: the problem

 1: How to construct an initial ordered queue

 2: How to combine two adjacent queues into an ordered queue

 3: How to complete a trip and merge (two kinds we only completed the previous adjacent)

 4: What is the sign of the end of the merger

Three: problem solving

1: an ordered sequence with an initial length of 1

2: The adjacent arrays are placed in the temporary array in order of size

/**
	 * 1: We regard the generation sorting sequence as n ordered sequences of length 1 2: How two adjacent ones are merged into an ordered sequence s: the first position of the first sequence m: the last of the first sequence a location
	 * t: a position in the second sequence k: the first position of the queue after merging
	 *
	 * We pass the original array, the temporary array, the first position of the ordered queue, the last position, and the second last position of the ordered queue
	 */
	public void merge(int r[], int r1[], int s, int m, int t) {
		int i, j, k;
		i = s;
		j = m + 1;
		k = s;
		while (i < m && j < t)
		{
			if (r[i] < r[j])
				r1[k++] = r[k++];
			else
				r1[k++] = r[j++];
		}
		// The first one has not been processed or the second one has not been processed
		if (i < m) {
			while (i < m)
				r1[k++] = r[i];
		} else {
			// The second array, not finished
			while (j < t)
				r1[k++] = r[j++];
		}
	}

Three: How to merge the rest of the trip

3.1: We divide into three cases

1: The merged is all the front

2: Merge to the end

    2.1: There is one remaining length less than h and length h

    2.2: Only one of length h remains

public void MergePass(int r[], int r1[], int n, int h) {
		int i = 1;
		/**
		 * 1: merge two lengths of h; 2: merge one H, the other is less than h (the end case) 3: merge from the remaining one h, we hang it in the merged array
		 */
		// 1: Merge ordered sequences of length h
		while (i < n - 2 * h + 1) {
			// See if 1 is subtracted, let's see if i is included
			merge(r, r1, i, i + h - 1, i + 2 * h - 1);
			// The value of i is shifted back by 2h
			i += 2 * h;
		}
		// 2: After merging to the end, there is an array of length less than h and an array of length h
		if (i < n - h + 1) {
			merge(r, r1, i, i + h - 1, n);
		} else {
			for (int k = i; k < n; k++) {
				r1[k] = r[k];
			}
		}

	}

Four: end sign

The initial length is 1, we judge whether the final queue length is n, as the end mark

	/**
    *End of judgment
    */
	public void MergeSort(int r[],int r1[],int n) {
		int h=1;
		while(h<n)
		{
			MergePass(r, r1, n, h);//The sorted array is placed in the temporary array
			h=2*h;
			MergePass(r1,r,n,h);//We pour the temporary array into our original array and
	        h=2*h;
		}
	}
	




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324623142&siteId=291194637