Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use merge sort

Shulou Source: shulou.com Published: 2022-06-03 06:13:12 09月18日 Update

This article introduces the relevant knowledge of "how to use merge sorting". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Merge sorting (Merge sort) is an effective sorting algorithm based on merge operation. This algorithm is a very typical application of divide-and-conquer (Divide and Conquer).

Merging and sorting is based on the idea of divide-and-conquer, which has three steps in each layer of recursion:

Divide (decomposition): divide n elements into a subsequence containing 2 elements.

Conquer: the recursive sorting of two subsequences by merging and sorting.

Combine: the sort result is obtained by merging two sorted subsequences.

As shown in the following figure:

The code is as follows:

Public static int [] sort (int [] arr) {if (arr.length)

< 2) { return arr; } int middle = arr.length / 2; int[] left = Arrays.copyOfRange(arr, 0, middle); int[] right = Arrays.copyOfRange(arr, middle, arr.length); //递归调用 return merge(sort(left), sort((right))); } private static int[] merge(int[] left, int[] right) { int leftLength = left.length; int rightLength = right.length; int[] result = new int[leftLength + rightLength]; int i = 0; while (left.length >

0 & & right.length > 0) {if (left [0] > right [0]) {result [iTunes +] = right [0]; right = Arrays.copyOfRange (right, 1, right.length);} else {result [iTunes +] = left [0]; left = Arrays.copyOfRange (left, 1, left.length) }} while (right.length > 0) {result [ionization +] = right [0]; right = Arrays.copyOfRange (right, 1, right.length);} while (left.length > 0) {result [ionization +] = left [0]; left = Arrays.copyOfRange (left, 1, left.length);} return result } the content of "how to use merge sorting" ends here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Sort sequence two element content more knowledge algorithm recursion practical effective successful next three code typical dilemma reality thought situation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information NVidia Linux Shulou Technology OPPO Reno