fork download
  1. import java.util.*;
  2.  
  3. public class Main {
  4.  
  5. public static void main(String[] args) {
  6.  
  7. int[] arr = {9,8,7,6,-5,-4,-31,2,1};
  8.  
  9. System.out.println("Input:");
  10. display(arr);
  11. mergesort(arr);
  12. System.out.println("\nOutput:");
  13. display(arr);
  14. System.out.println("\n");
  15. }
  16.  
  17. public static void display(int arr[]) {
  18.  
  19. for(int value: arr) {
  20.  
  21. System.out.print(value + " ");
  22. }
  23. }
  24.  
  25. public static void mergesort(int[] arr) {
  26. divideEtImpera(0,arr.length-1,arr);
  27. }
  28.  
  29. public static void divideEtImpera(int lo, int hi, int arr[]) {
  30. if(lo == hi) return;
  31. int middle = (lo+hi)>>1;
  32. divideEtImpera(lo,middle, arr);
  33. divideEtImpera(middle+1,hi,arr);
  34. merge(lo,middle,hi,arr);
  35. }
  36.  
  37. public static void merge(int lo, int m, int hi, int[] vec) {
  38. int i=lo, j=m+1, k = 0;
  39. int aux[] = new int[hi-lo+1];
  40. while(i<=m && j<=hi) {
  41. if(vec[i]<vec[j]) aux[k++] = vec[i++];
  42. else aux[k++] = vec[j++];
  43. }
  44. while(i<=m) aux[k++] = vec[i++];
  45. while(j<=hi) aux[k++] = vec[j++];
  46. k = 0;
  47. for(int index=lo;index<=hi;index++) vec[index] = aux[k++];
  48. }
  49. }
  50.  
Success #stdin #stdout 0.15s 53620KB
stdin
Standard input is empty
stdout
Input:
9 8 7 6 -5 -4 -31 2 1 
Output:
-31 -5 -4 1 2 6 7 8 9