Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package Interesting;
- import java.util.*;
- public class Merge {
- public static void merge(int[] a, int i, int c, int j){
- int b[] = new int[a.length];
- int l = i;
- int r = j;
- int k = c+1;
- int t = i;
- while (i <= c && k <= j){
- if (a[i] < a[k]){
- b[t] = a[i];
- i++;
- }
- else{
- b[t] = a[k];
- k++;
- }
- t++;
- }
- while (i <= c){
- b[t] = a[i];
- i++;
- t++;
- }
- while (k <= j){
- b[t] = a[k];
- k++;
- t++;
- }
- for (int e = l; e <= r; e++){
- a[e] = b[e];
- }
- }
- public static void mergeSort(int[] a, int i, int j){
- if (i < j){
- int c = (i + j) / 2;
- mergeSort(a, i, c);
- mergeSort(a, c+1, j);
- merge(a, i, c, j);
- }
- }
- public static void main(String[] args){
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int a[] = new int[n];
- for (int l = 0; l < n; l++)
- a[l] = sc.nextInt();
- mergeSort(a, 0, n-1);
- for (int l = 0; l < n; l++)
- System.out.print(a[l] + " ");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement