1+ import java .util .*;
2+
3+ class Solution {
4+ private static void merge (int [] arr , int low , int mid , int high ) {
5+ ArrayList <Integer > temp = new ArrayList <>(); // temporary array
6+ int left = low ; // starting index of left half of arr
7+ int right = mid + 1 ; // starting index of right half of arr
8+
9+ //storing elements in the temporary array in a sorted manner//
10+
11+ while (left <= mid && right <= high ) {
12+ if (arr [left ] <= arr [right ]) {
13+ temp .add (arr [left ]);
14+ left ++;
15+ } else {
16+ temp .add (arr [right ]);
17+ right ++;
18+ }
19+ }
20+
21+ // if elements on the left half are still left //
22+
23+ while (left <= mid ) {
24+ temp .add (arr [left ]);
25+ left ++;
26+ }
27+
28+ // if elements on the right half are still left //
29+ while (right <= high ) {
30+ temp .add (arr [right ]);
31+ right ++;
32+ }
33+
34+ // transfering all elements from temporary to arr //
35+ for (int i = low ; i <= high ; i ++) {
36+ arr [i ] = temp .get (i - low );
37+ }
38+ }
39+
40+ public static void mergeSort (int [] arr , int low , int high ) {
41+ if (low >= high ) return ;
42+ int mid = (low + high ) / 2 ;
43+ mergeSort (arr , low , mid ); // left half
44+ mergeSort (arr , mid + 1 , high ); // right half
45+ merge (arr , low , mid , high ); // merging sorted halves
46+ }
47+ }
48+ public class tUf {
49+ public static void main (String args []) {
50+ Scanner sc = new Scanner (System .in );
51+ int n = 7 ;
52+ int arr [] = { 9 , 4 , 7 , 6 , 3 , 1 , 5 };
53+ System .out .println ("Before sorting array: " );
54+ for (int i = 0 ; i < n ; i ++) {
55+ System .out .print (arr [i ] + " " );
56+ }
57+ System .out .println ();
58+ Solution .mergeSort (arr , 0 , n - 1 );
59+ System .out .println ("After sorting array: " );
60+ for (int i = 0 ; i < n ; i ++) {
61+ System .out .print (arr [i ] + " " );
62+ }
63+ System .out .println ();
64+ }
65+
66+ }
0 commit comments