Mergesort: merging two arrays into a third : Sort « Collections « Java Tutorial






public class MainClass {
  public static void main(String[] args) {
    int[] arrayA = { 23, 47, 81, 95 };
    int[] arrayB = { 7, 14, 39, 55, 62, 74 };
    int[] arrayC = new int[10];

    merge(arrayA, arrayA.length, arrayB, arrayB.length, arrayC);
    for (int i : arrayC) {
      System.out.println(i);

    }
  }

  public static void merge(int[] arrayA, int sizeA, int[] arrayB, int sizeB, int[] arrayC) {
    int arrayAIndex = 0, arrayBIndex = 0, arrayCIndex = 0;

    while (arrayAIndex < sizeA && arrayBIndex < sizeB)
      if (arrayA[arrayAIndex] < arrayB[arrayBIndex])
        arrayC[arrayCIndex++] = arrayA[arrayAIndex++];
      else
        arrayC[arrayCIndex++] = arrayB[arrayBIndex++];

    while (arrayAIndex < sizeA)
      arrayC[arrayCIndex++] = arrayA[arrayAIndex++];

    while (arrayBIndex < sizeB)
      arrayC[arrayCIndex++] = arrayB[arrayBIndex++];
  }
}
7
14
23
39
47
55
62
74
81
95








9.53.Sort
9.53.1.Bubble Sort
9.53.2.Selection Sort
9.53.3.Insertion Sort
9.53.4.Sorting Objects using insertion sort
9.53.5.Mergesort: merging two arrays into a third
9.53.6.Generic Merge Sorter with generic Comparator
9.53.7.Shellsort
9.53.8.Quicksort: simple version of quick sort
9.53.9.Quick sort with median-of-three partitioning
9.53.10.Quick sort: uses an insertion sort to handle subarrays of fewer than 10 cells