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
| import java.util.*;
public class Main {
private static void mergeSort(int[] arr) { int[] temp = new int[arr.length]; mergeSort(arr, temp, 0, arr.length - 1); }
private static void mergeSort(int[] arr, int[] temp, int start, int end) {
if(start < end) { int mid = (start + end) / 2;
mergeSort(arr, temp, start, mid); mergeSort(arr, temp, mid + 1, end);
merge(arr, temp, start, mid, end); } }
private static void merge(int[] arr, int[] temp, int start, int mid, int end) {
for (int i = start; i <= end; i++) { temp[i] = arr[i]; }
int part1 = start; int part2 = mid + 1; int index = start;
while (part1 <= mid && part2 <= end) { if(temp[part1] <= temp[part2]) { arr[index] = temp[part1]; part1++; } else { arr[index] = temp[part2]; part2++; } index++; }
for(int i = 0; i <= mid-part1; i++) { arr[index + i] = temp[part1 + i]; } }
public static void main(String args[]){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n];
for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); }
mergeSort(arr);
for (int i = 0; i < n; i++) { System.out.println(arr[i]); } sc.close(); }
}
|