Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Ex08 {
- public static int[] copy(int[] arr, int start, int end) {
- int[] res = new int[end - start + 1];
- for (int i = 0; i < res.length; i++) {
- res[i] = arr[start + i];
- }
- return res;
- }
- public static int[] merge(int[] arr1, int[] arr2) {
- int[] res = new int[arr1.length + arr2.length];
- int p1 = 0;
- int p2 = 0;
- int p3 = 0;
- while (p1 < arr1.length && p2 < arr2.length) {
- if (arr1[p1] <= arr2[p2]) {
- res[p3] = arr1[p1];
- p1 += 1;
- p3 += 1;
- } else {
- res[p3] = arr2[p2];
- p2 += 1;
- p3 += 1;
- }
- }
- while (p1 < arr1.length) {
- res[p3] = arr1[p1];
- p1 += 1;
- p3 += 1;
- }
- while (p2 < arr2.length) {
- res[p3] = arr2[p2];
- p2 += 1;
- p3 += 1;
- }
- System.out.println(asString(arr1) + " and " + asString(arr2) + " was merged to " + asString(res));
- return res;
- }
- public static int[] mergeSort(int[] arr) {
- System.out.println("start sorting " + asString(arr));
- if (arr.length == 1) {
- System.out.println(asString(arr) + " was sorted " + asString(arr));
- return arr;
- }
- int mid = arr.length / 2;
- int[] left = copy(arr, 0, mid - 1);
- int[] right = copy(arr, mid, arr.length - 1);
- int[] res;
- // sort . . . .
- int[] sortedLeft = mergeSort(left);
- int[] sortedRight = mergeSort(right);
- res = merge(sortedLeft, sortedRight);
- System.out.println(asString(arr) + " was sorted " + asString(res));
- return res;
- }
- public static String asString(int[] arr) {
- String res = "[";
- for (int i = 0; i < arr.length; i++) {
- res += arr[i] + " ";
- }
- res += "]";
- return res;
- }
- public static void main(String[] args) {
- int[] arr = { 1, 90, 2, 21, 9, 13, 1, 2, 4 };
- int[] res; // = {1, 1, 2, 4,5,6,7,8,9,13,21,90};
- System.out.println("source data : " + asString(arr));
- res = mergeSort(arr);
- System.out.println("the sorted data : " + asString(res));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement