Advertisement
deced

Untitled

Nov 8th, 2020
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.31 KB | None | 0 0
  1. package com.company;
  2.  
  3. public class Main {
  4.     public static int[] Merge(int[] left, int[] right) {
  5.         int[] answer = new int[left.length + right.length];
  6.         int i1 = 0;
  7.         int i2 = 0;
  8.         for (int i = 0; i < answer.length; i++) {
  9.             if (i2 == right.length||(i1 < left.length && left[i1] < right[i2])) {
  10.                 answer[i] = left[i1];
  11.                 i1++;
  12.             } else {
  13.                 answer[i] = right[i2];
  14.                 i2++;
  15.             }
  16.         }
  17.         return answer;
  18.     }
  19.  
  20.     public static int[] mergeSort(int[] toSort) {
  21.         if (toSort.length > 1){
  22.             int[] left = new int[(toSort.length / 2) + toSort.length % 2];
  23.             int[] right = new int[toSort.length / 2];
  24.             int j = 0;
  25.             for (int i = 0; i < left.length; i++) {
  26.                 left[i] = toSort[j];
  27.                 j++;
  28.             }
  29.             for (int i = 0; i < right.length; i++) {
  30.                 right[i] = toSort[j];
  31.                 j++;
  32.             }
  33.             toSort = Merge(mergeSort(left), mergeSort(right));
  34.         }
  35.         return toSort;
  36.     }
  37.  
  38.     public static void main(String[] args) {
  39.         int[] a = new int[]{4234,715,7,885,532,55896523,5468793,57881,4355778,66,3523,35794524,6586743};
  40.        a = mergeSort(a);
  41.     }
  42.  
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement