📜  Java程序以实现合并排序算法

📅  最后修改于: 2020-09-26 18:54:34             🧑  作者: Mango

在此示例中,我们将学习在Java中执行合并排序算法。

示例:实现合并排序算法的Java程序
import java.util.Arrays;

// Merge sort in Java

class Main {

  // Merge two sub arrays L and M into array
  void merge(int array[], int p, int q, int r) {

    int n1 = q - p + 1;
    int n2 = r - q;

    int L[] = new int[n1];
    int M[] = new int[n2];

    // fill the left and right array
    for (int i = 0; i < n1; i++)
      L[i] = array[p + i];
    for (int j = 0; j < n2; j++)
      M[j] = array[q + 1 + j];

    // Maintain current index of sub-arrays and main array
    int i, j, k;
    i = 0;
    j = 0;
    k = p;

    // Until we reach either end of either L or M, pick larger among
    // elements L and M and place them in the correct position at A[p..r]
    // for sorting in descending
    // use if(L[i] >= 

输出1

Unsorted Array:
[6, 5, 12, 10, 9, 1]
Sorted Array:
[1, 5, 6, 9, 10, 12]

在此,数组的元素按升序排序。如果要按降序对元素进行排序,则可以在merge()方法的第一个while循环内, merge()代码更改为:

// the less than sign is changed to greater than
if (L[i] >= M[j]) {

如果您想了解有关合并排序算法的更多信息,请访问合并排序算法。