search
HomeJavajavaTutorialWhat is the principle of merge sort algorithm in Java and how to implement it

    1. Basic idea

    Merge sort is an effective sorting algorithm based on merge operations. This algorithm is a very typical application using the divide and conquer method (Divide and Conquer). Merge the already ordered subsequences to obtain a completely ordered sequence; that is, first make each subsequence orderly, and then make the subsequence segments orderly. If two ordered lists are merged into one ordered list, it is called a 2-way merge.

    2. Algorithm analysis

    1. Algorithm description

    Divide the input sequence of length n into two subsequences of length n/2; for these two subsequences Merge sorting is used respectively; two sorted subsequences are merged into a final sorting sequence.

    2. Process Analysis

    (1). Now we will split items [1] (index from 0 to 0, both sides included) and [28] index from 1 to 1, Both sides included) are merged together.

    What is the principle of merge sort algorithm in Java and how to implement it

    (2), because 1 (left split)

    What is the principle of merge sort algorithm in Java and how to implement it

    (3) Since the left split is empty, we copy 28 (right split) into a new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (4). We copy the elements in the new array back to the original array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (5), because 3 (left split)

    What is the principle of merge sort algorithm in Java and how to implement it

    (6). Because the left split is empty, we copy 21 (right split) into a new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (7), Now we will split the terms [1,28] (index from 0 to 1, both sides included) and [3,21] with index from 2 to 3, both sides included) merged together.

    What is the principle of merge sort algorithm in Java and how to implement it

    (8), because 1 (left split)

    What is the principle of merge sort algorithm in Java and how to implement it

    (9), because 28 (left split) > 3 (right split), we copy {rightPart} into a new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (10), because 28 (left split) > 21 (right split), we copy {rightPart} into a new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (11), because the right split is empty, we copy 28 (left split) into the new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    # (12), we copy the elements in the new array back to the original array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (13), Now we will split the terms [11] (index from 4 to 4, both sides included) and [7] with index from 5 to 5, both sides All included) are merged together.

    What is the principle of merge sort algorithm in Java and how to implement it

    (14), because 11 (left split) > 7 (right split), we copy {rightPart} into a new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (15), because the right split is empty, we copy 11 (left split) into the new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (16). We copy the elements in the new array back to the original array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (17), and so on

    (18), because 1 (left split)

    What is the principle of merge sort algorithm in Java and how to implement it

    (19), because 3 (left split)

    What is the principle of merge sort algorithm in Java and how to implement it

    (20), because 21 (left split) > 6 (right split), we copy {rightPart} into a new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    (21), because 21 (left split) > 7 (right split), we copy {rightPart} into a new array.

    What is the principle of merge sort algorithm in Java and how to implement it

    # (22), and so on, we copy the elements in the new array back to the original array.

    What is the principle of merge sort algorithm in Java and how to implement it

    3. GIF demonstration

    What is the principle of merge sort algorithm in Java and how to implement it

    3. Algorithm implementation

    package com.algorithm.tenSortingAlgorithm;
    
    import java.util.Arrays;
    
    public class MergeSort {
        private static void mergeSort(int[] arr, int low, int high) {
            if (low < high) { //当子序列中只有一个元素时结束递归
                int mid = (low + high) / 2; //划分子序列
                mergeSort(arr, low, mid); //对左侧子序列进行递归排序
                mergeSort(arr, mid + 1, high); //对右侧子序列进行递归排序
                merge(arr, low, mid, high); //合并
            }
        }
    
        private static void merge(int[] arr, int low, int mid, int high) {
            int[] temp = new int[arr.length]; //辅助数组
            int k = 0, i = low, j = mid + 1; //i左边序列和j右边序列起始索引,k是存放指针
            while (i <= mid && j <= high) {
                if (arr[i] <= arr[j]) {
                    temp[k++] = arr[i++];
                } else {
                    temp[k++] = arr[j++];
                }
            }
            //如果第一个序列未检测完,直接将后面所有元素加到合并的序列中
            while (i <= mid) {
                temp[k++] = arr[i++];
            }
            //同上
            while (j <= high) {
                temp[k++] = arr[j++];
            }
            //复制回原数组
            for (int t = 0; t < k; t++) {
                arr[low + t] = temp[t];
            }
        }
    
        public static void main(String[] args) {
            int[] arr = {1,28,3,21,11,7,6,18};
            mergeSort(arr, 0, arr.length - 1);
            System.out.println(Arrays.toString(arr));
        }
    }

    The above is the detailed content of What is the principle of merge sort algorithm in Java and how to implement it. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

    JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

    Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

    JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

    What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

    Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

    Are there any areas where Java requires platform-specific configuration or tuning?Are there any areas where Java requires platform-specific configuration or tuning?Apr 29, 2025 am 12:11 AM

    Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

    What are some tools or libraries that can help you address platform-specific challenges in Java development?What are some tools or libraries that can help you address platform-specific challenges in Java development?Apr 29, 2025 am 12:01 AM

    OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

    How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

    JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

    Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

    Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

    Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

    The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

    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

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    WebStorm Mac version

    WebStorm Mac version

    Useful JavaScript development tools

    SAP NetWeaver Server Adapter for Eclipse

    SAP NetWeaver Server Adapter for Eclipse

    Integrate Eclipse with SAP NetWeaver application server.

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    mPDF

    mPDF

    mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),