-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
c62709d
commit d7c0c1f
Showing
1 changed file
with
78 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,78 @@ | ||
//Merge sort | ||
|
||
import java.util.*; | ||
|
||
class Merge_Sort { | ||
static void printArray(int arr[]) { | ||
StringBuffer sb=new StringBuffer(""); | ||
int n = arr.length; | ||
|
||
for(int i = 0; i < n; ++i) | ||
sb.append(arr[i] + " "); | ||
|
||
System.out.println(sb.toString()); | ||
} | ||
|
||
public static void main(String args[]) { | ||
Scanner sc = new Scanner(System.in); | ||
int T = sc.nextInt(); | ||
|
||
while(T > 0) { | ||
int n = sc.nextInt(); | ||
Merge_Sort ms = new Merge_Sort(); | ||
int arr[] = new int[n]; | ||
|
||
for(int i = 0; i < n; i++) | ||
arr[i] = sc.nextInt(); | ||
|
||
Solution g = new Solution(); | ||
g.mergeSort(arr, 0, arr.length - 1); | ||
ms.printArray(arr); | ||
T--; | ||
} | ||
} | ||
} | ||
|
||
class Solution { | ||
void merge(int arr[], int l, int m, int r) { | ||
ArrayList<Integer> temp = new ArrayList<>(); | ||
int left = l; | ||
int right = m + 1; | ||
|
||
while(left <= m && right <= r) { | ||
if(arr[left] <= arr[right]) { | ||
temp.add(arr[left]); | ||
left++; | ||
} | ||
else { | ||
temp.add(arr[right]); | ||
right++; | ||
} | ||
} | ||
|
||
while(left <= m) { | ||
temp.add(arr[left]); | ||
left++; | ||
} | ||
|
||
while(right <= r) { | ||
temp.add(arr[right]); | ||
right++; | ||
} | ||
|
||
for(int i = l; i <= r; i++) { | ||
arr[i] = temp.get(i - l); | ||
} | ||
} | ||
|
||
void mergeSort(int arr[], int l, int r) { | ||
if(l >= r) { | ||
return; | ||
} | ||
|
||
int mid = (l + r) / 2; | ||
mergeSort(arr, l, mid); | ||
mergeSort(arr, mid + 1, r); | ||
merge(arr, l, mid, r); | ||
} | ||
} |