1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| package homework;
import java.util.Scanner; import java.util.regex.Pattern;
public class Homework_MergeSort {
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine().toString(); String arr[] = str.split(" "); if(isInteger(arr[0])) { int a[] = new int[arr.length]; for (int j = 0; j < a.length; j++) { a[j] = Integer.parseInt(arr[j]); } int len = arr.length; int[] result = new int[len]; mergeSort(a, result, 0, len - 1); for (int j = 0; j < a.length; j++) { System.out.print(a[j] + " "); } }else if (isDouble(arr[0])) { double a[] = new double[arr.length]; for (int j = 0; j < a.length; j++) { a[j] = Double.parseDouble(arr[j]); } int len = arr.length; double[] result = new double[len]; mergeSort(a, result, 0, len - 1); for (int j = 0; j < a.length; j++) { System.out.print(a[j] + " "); } }else { ; } sc.close(); }
private static boolean isInteger(String str) { if (null == str || "".equals(str)) { return false; } Pattern pattern = Pattern.compile("^[-\\+]?[\\d]*$"); return pattern.matcher(str).matches(); }
private static boolean isDouble(String str) { if (null == str || "".equals(str)) { return false; } Pattern pattern = Pattern.compile("^[-\\+]?\\d*[.]\\d+$"); return pattern.matcher(str).matches(); }
static void mergeSort(int[] arr, int[] result, int start, int end) { if (start >= end) return; int len = end - start, mid = (len >> 1) + start; int start1 = start, end1 = mid; int start2 = mid + 1, end2 = end; mergeSort(arr, result, start1, end1); mergeSort(arr, result, start2, end2); int k = start; while (start1 <= end1 && start2 <= end2) result[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++]; while (start1 <= end1) result[k++] = arr[start1++]; while (start2 <= end2) result[k++] = arr[start2++]; for (k = start; k <= end; k++) arr[k] = result[k]; } static void mergeSort(double[] arr, double[] result, int start, int end) { if (start >= end) return; int len = end - start, mid = (len >> 1) + start; int start1 = start, end1 = mid; int start2 = mid + 1, end2 = end; mergeSort(arr, result, start1, end1); mergeSort(arr, result, start2, end2); int k = start; while (start1 <= end1 && start2 <= end2) result[k++] = arr[start1] < arr[start2] ? arr[start1++] : arr[start2++]; while (start1 <= end1) result[k++] = arr[start1++]; while (start2 <= end2) result[k++] = arr[start2++]; for (k = start; k <= end; k++) arr[k] = result[k]; }
}
|