Advertisement
Guest User

Untitled

a guest
Feb 22nd, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Merge_sort_vinil {
  4.  
  5. public static void main(String[] args) {
  6. // taking static integer array for the sorting method
  7. int[] input_List = {4, 2, 6, 5, 11, 9, 98, 89};
  8. System.out.println("before Mergesort : " + Arrays.toString(input_List)); // printing array elements
  9. sortMethod(input_List);
  10. System.out.println("after Mergesort: " + Arrays.toString(input_List));
  11. }
  12. // this method takes the input parameter
  13. public static void sortMethod(int[] array) {
  14. if (array.length > 1) {
  15. // splitting input array into two
  16. int[] left = leftHalfArray(array);
  17. int[] right = rightHalfArray(array);
  18.  
  19. sortMethod(left); // applying
  20. sortMethod(right);
  21.  
  22. // merge the sorted halves into a sorted whole
  23. mergingMethod(array, left, right);
  24. }
  25. }
  26.  
  27. // copying first half array into left[].
  28. public static int[] leftHalfArray(int[] array) {
  29. int size1 = array.length / 2;
  30. int[] leftArray = new int[size1];
  31. for (int i = 0; i < size1; i++) {
  32. leftArray[i] = array[i];
  33. }
  34. return leftArray;
  35. }
  36.  
  37. // copying second half array into right[]
  38. public static int[] rightHalfArray(int[] array) {
  39. int size1 = array.length / 2;
  40. int size2 = array.length - size1;
  41. int[] rightArray = new int[size2];
  42. for (int i = 0; i < size2; i++) {
  43. rightArray[i] = array[i + size1];
  44. }
  45. return rightArray;
  46. }
  47.  
  48. //this method compares the left array elements with right array and swaps them accordingly to make result array.
  49. static void mergingMethod(int[] result, int[] left, int[] right) {
  50. int leftIndex = 0; // index into left array
  51. int rightIndex = 0; // index into right array
  52.  
  53. // looping through the size of input array
  54. for (int i = 0; i < result.length; i++) {
  55. if (rightIndex >= right.length || (leftIndex < left.length && left[leftIndex] <= right[rightIndex]))
  56. {
  57. result[i] = left[leftIndex]; // sorting in the left array
  58. leftIndex++;
  59. } else {
  60. result[i] = right[rightIndex]; // sorting right array
  61. rightIndex++;
  62. }
  63. }
  64. }
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement