Advertisement
Viniciusfelbs

Mergesort

Oct 8th, 2020
915
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.67 KB | None | 0 0
  1. import java.util.Arrays;
  2. import java.util.Scanner;
  3.  
  4. public class Mergesort {
  5.     public static void main(String[] args) {
  6.         Scanner s = new Scanner(System.in);
  7.         int quantEntrada = Integer.parseInt(s.nextLine());
  8.         String[] vetor = s.nextLine().split("\\|");
  9.         int[] aux1 = new int[quantEntrada];
  10.         int[] aux = new int[quantEntrada];
  11.         System.out.println(Arrays.toString(msort(conversao(vetor,aux), aux1,0, quantEntrada -1)));
  12.     }
  13.     public static int[] conversao(String [] vetor, int[] aux){
  14.         int j = 0;
  15.         for (String a : vetor) {
  16.             aux[j++] = Integer.parseInt(a);
  17.         }
  18.         return aux;
  19.     }
  20.  
  21.     public static int[] msort(int[] vetor, int[] aux, int valorI, int valorF) {
  22.         if (valorI < valorF) {
  23.             int meio = (valorI + valorF)/2;
  24.             msort(vetor, aux, valorI, meio);
  25.             msort(vetor, aux,meio + 1, valorF);
  26.             intercalacao(vetor, aux, valorI, meio, valorF);
  27.         }
  28.         return vetor;
  29.     }
  30.  
  31.     public static void intercalacao(int[] vetor, int[]aux, int valorI, int meio, int valorF) {
  32.         int i = valorI;
  33.         int j = meio + 1;
  34.         for (int count = valorI; count <= valorF; count++)
  35.             aux[count] = vetor[count];
  36.         for (int count1 = valorI; count1 <= valorF; count1++) {
  37.             if (i > meio) {
  38.                 vetor[count1] = aux[j++];
  39.  
  40.             } else if (j > valorF) {
  41.                 vetor[count1] = aux[i++];
  42.  
  43.             } else if (aux[i] > aux[j]) {
  44.                 vetor[count1] = aux[j++];
  45.  
  46.             } else {
  47.                 vetor[count1] = aux[i++];
  48.             }
  49.  
  50.         }
  51.     }
  52. }
  53.  
  54.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement