search
HomeJavajavaTutorialjava data structure sorting algorithm (2) merge sort

java data structure sorting algorithm (2) merge sort

May 31, 2017 am 09:29 AM
javamerge sortdata structurealgorithm

This article mainly introduces the merge sort of Java data structure sorting algorithm. It analyzes the principles, implementation techniques and related precautions of merge sort in detail based on specific examples. Friends in need can refer to this article

The example describes the merge sort of Java data structure sorting algorithm. Share it with everyone for your reference, the details are as follows:

The sorts of sorting mentioned above all arrange a group of records into an orderly sequence according to the size of the keywords, and the idea of ​​merge sorting is: based on Merge, merge two or more ordered lists into a new ordered list

Merge sort algorithm:Assume that the initial sequence contains n records, First, treat these n records as n ordered subsequences, each subsequence has a length of 1, and then merge them in pairs to get n/2 lengths of 2 (when n is an odd number, the length of the last sequence is 1 ) ordered subsequence. On this basis, the ordered subsequences of length 2 are then merged brightly to obtain several ordered subsequences of length 4. Repeat this until an ordered sequence of length n is obtained. This method is called: 2-way merge sort (the basic operation is to merge two adjacent ordered subsequences in the sequence to be sorted into an ordered sequence).

Algorithm implementation code is as follows:

package exp_sort;
public class MergeSort {
  /**
   * 相邻两个有序子序列的合并算法
   *
   * @param src_array
   * @param low
   * @param high
   * @param des_array
   */
  public static void Merge(int src_array[], int low, int high,
      int des_array[]) {
    int mid;
    int i, j, k;
    mid = (low + high) / 2;
    i = low;
    k = 0;
    j = mid + 1;
    // compare two list
    while (i <= mid && j <= high) {
      if (src_array[i] <= src_array[j]) {
        des_array[k] = src_array[i];
        i = i + 1;
      } else {
        des_array[k] = src_array[j];
        j = j + 1;
      }
      k = k + 1;
    }
    // if 1 have,cat
    while (i <= mid) {
      des_array[k] = src_array[i];
      k = k + 1;
      i = i + 1;
    }
    while (j <= high) {
      des_array[k] = src_array[j];
      k = k + 1;
      j = j + 1;
    }
    for (i = 0; i < k; i++) {
      src_array[low + i] = des_array[i];
    }
  }
  /**
   * 2-路归并排序算法,递归实现
   *
   * @param src_array
   * @param low
   * @param high
   * @param des_array
   */
  public static void mergeSort(int src_array[], int low, int high,
      int des_array[]) {
    int mid;
    if (low < high) {
      mid = (low + high) / 2;
      mergeSort(src_array, low, mid, des_array);
      mergeSort(src_array, mid + 1, high, des_array);
      Merge(src_array, low, high, des_array);
    }
  }
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    int array1[] = { 38, 62, 35, 77, 55, 14, 35, 98 };
    int array2[] = new int[array1.length];
    mergeSort(array1, 0, array1.length - 1, array2);
    System.out.println("\n----------after sort-------------");
    for (int ii = 0; ii < array1.length; ii++) {
      System.out.print(array1[ii] + " ");
    }
    System.out.println("\n");
  }
}

Code explanation:

In merge sort, a merge requires multiple calls to the 2-way merge algorithm. The time complexity of a merge is O(n). The time to merge two sorted tables is obviously linear, because at most n-1 comparisons are made, where n is the total number of elements. If there are multiple numbers, that is, when n is not 1, recursively merge and sort the first half of the data and the second half of the data to obtain the two parts of sorted data, and then merge them together.

Algorithm analysis:

This algorithm is based on the merge operation (also called the merge algorithm, which refers to the process of combining two sorted sequences An efficient sorting algorithm based on the operation of merging into a sequence). This algorithm is a very typical application of the divide and conquer method (pide and Conquer). It divides the problem into some small problems and then solves them recursively, and the conquering stage is solved by dividing the divided stage. Each answer fits together; divide and conquer is a very powerful use of recursion. Note: Compared with quick sort and heap sort, the biggest feature of merge sort is that it is a stable sorting method. The speed is second only to quick sort, and it is generally used for arrays that are generally disordered but whose sub-items are relatively ordered.

Complexity:

Time complexity is: O(nlogn)——This algorithm is the best and most efficient Bad and average time performance.
The space complexity is: O(n)
The number of comparison operations is between (nlogn) / 2 and nlogn - n + 1.
The number of assignment operations is (2nlogn). The space complexity of the merge algorithm is: 0 (n)
It is difficult to use in main memory sorting (merge sort takes up more memory. The main problem is that merging two sorted tables requires linear additional memory, which also costs money in the entire algorithm. Some additional operations such as copying data to a temporary array and then copying it back will seriously slow down the sorting speed) but it is very efficient and is mainly used for external sorting and for important internal sorting applications. , generally choose quick sort.

The steps for the merge operation are as follows:

Step 1: Apply for space so that its size is the sum of the two sorted sequences. The space is used to store the merged sequence
Step 2: Set two pointers, the initial positions are the starting positions of the two sorted sequences
Step 3: Compare the elements pointed to by the two pointers, Select a relatively small element and put it into the merge space, and move the pointer to the next position
Repeat step 3 until a certain pointer reaches the end of the sequence
Copy all the remaining elements of the other sequence directly to the end of the merge sequence

The steps of merge sorting are as follows (assuming that the sequence has n elements in total):

merge every two adjacent numbers in the sequence (merge ), forming floor(n/2) sequences, each sequence contains two elements after sorting
Merge the above sequences again, forming floor(n/4) sequences, each sequence contains four elements
Repeat step 2 until all elements are sorted

[Related recommendations]

1. Java data structure sorting algorithm (1) Tree selection sort

2. Detailed explanation of the example tutorial of Selection Sort_java in Java

3. Java data structure sorting algorithm (3) Simple selection sort

4. java data structure sorting algorithm (4) selection sort

The above is the detailed content of java data structure sorting algorithm (2) merge sort. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log?Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to elegantly obtain entity class variable names to build database query conditions?How to elegantly obtain entity class variable names to build database query conditions?Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list?How to use the Redis cache solution to efficiently realize the requirements of product ranking list?Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

How to safely convert Java objects to arrays?How to safely convert Java objects to arrays?Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

How do I convert names to numbers to implement sorting and maintain consistency in groups?How do I convert names to numbers to implement sorting and maintain consistency in groups?Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products?Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to set the default run configuration list of SpringBoot projects in Idea for team members to share?How to set the default run configuration list of SpringBoot projects in Idea for team members to share?Apr 19, 2025 pm 11:24 PM

How to set the SpringBoot project default run configuration list in Idea using IntelliJ...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software