-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmergeSort.java
More file actions
56 lines (47 loc) · 1.13 KB
/
mergeSort.java
File metadata and controls
56 lines (47 loc) · 1.13 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
import java.util.Scanner;
import java.util.*;
public class mergeSort {
public static int[] merge(int arr1[], int arr2[]){
int merged[]= new int [arr1.length+arr2.length];
for (int i = 0; i < arr1.length; i++) {
merged[i]=arr1[i];
}
for (int j=0; j< arr2.length; j++){
merged[arr1.length+j]=arr2[j];
}
Arrays.sort(merged);
return merged;
}
public static void printArray(int a[]) {
for (int j=0;j<a.length;j++){
System.out.print(a[j]);
}
}
public static int[] mergeSort(int[] input){
//Base case
if(input.length==1){
return input;
}
//Created 2 new arrays and copied elements
int a1[]=new int[input.length/2];
int a2[]=new int[input.length-(input.length/2)];
for (int i=0;i<input.length/2;i++){
a1[i]=input[i];
}
for (int i=0;i<input.length-input.length/2;i++){
a2[i]=input[(input.length/2)+i];
}
//called recursion on 2 arrays
mergeSort (a1);
mergeSort (a2);
//merged sorted arrays
int sorted[]=merge(a1,a2);
return sorted;
//printArray(sorted);
}
public static void main(String[] args) {
int a[]={6,5,4,7,8,3,3,2,1,0};
int b[]=mergeSort(a);
printArray(b);
}
}