-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergesort.java
More file actions
62 lines (51 loc) · 1.55 KB
/
Mergesort.java
File metadata and controls
62 lines (51 loc) · 1.55 KB
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
import java.util.Scanner;
public class Mergesort {
public static void conquer(int arr[], int si, int mid, int ei){
int merged[]=new int[ei-si+1];
int idx1 = si;
int idx2 = mid+1;
int x = 0;
while(idx1 <= mid && idx2 <= ei){
if(arr[idx1] <= arr[idx2]) {
merged[x++] = arr[idx1++];
} else{
merged[x++] = arr[idx2++];
}
}
while(idx1 <= mid){
merged[x++] = arr[idx1++];
}
while(idx2 <= ei){
merged[x++] = arr[idx2++];
}
for(int i=0, j=si; i<merged.length; i++, j++){
arr[j]=merged[i];
}
}
public static void divide(int arr[],int si,int ei){
if(si>=ei){
return;
}
int mid = si + (ei-si)/2;
divide(arr, si, mid);
divide(arr, mid+1, ei);
conquer(arr, si, mid, ei);
}
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of elements: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter " + n + " elements:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
divide(arr, 0, n - 1);
System.out.println("Sorted array:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
sc.close();
}
}