forked from aswinkumarrk/data-structures
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMergeSort.java
More file actions
115 lines (100 loc) · 2.67 KB
/
MergeSort.java
File metadata and controls
115 lines (100 loc) · 2.67 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package com.geeksforgeeks.array;
import com.competitive.coding.spoj.InversionCount;
public class MergeSort
{
public static void main( String[] args )
{
int[] sample = {-12, 11, -13, -5, 6, -7, 5, -3, -6};
// int[] sample = {2, 4, 1, 3, 5};
// int[] sample = {1, 20, 6, 4, 5};
System.out.println( "Inversion Count is " + mergeSort( sample, 0, 4 ) );
System.out.println( "After sorting is " );
ArrayRotation.printArray( sample );
}
public static int mergeSort( int[] arr, int low, int high )
{
int inversionCount = 0;
if( low < high )
{
int mid = low + (high - low) / 2;
inversionCount = mergeSort( arr, low, mid );
inversionCount += mergeSort( arr, mid + 1, high );
inversionCount += merge1( arr, low, mid, high );
}
return inversionCount;
}
// My Own Implementation + to handle Inversion Count as well
private static int merge1( int[] arr, int low, int mid, int high )
{
int inversionCount = 0;
int t1 = low;
int t2 = mid + 1;
int N1 = mid;
int N2 = high;
int[] sortedArr = new int[(high - low) + 1];
int sortedCounter = 0;
while( t1 <= N1 && t2 <= N2 )
{
if( arr[t1] <= arr[t2] )
{
sortedArr[sortedCounter++] = arr[t1++];
}
else
{
sortedArr[sortedCounter++] = arr[t2++];
// if arr[t1] > arr[t2] then there at total of Middle - t1 inversions.
// as till t1 to middle is already sorted, So if arr[t1] > arr[t2] i.e. arr[t+1.....mid] > arr[t2]
// So those many inversions
inversionCount += mid + 1 - t1;
}
}
// Let's check whether either of t1 and t2 is still left
while( t1 <= N1 )
{
sortedArr[sortedCounter++] = arr[t1++];
}
while( t2 <= N2 )
{
sortedArr[sortedCounter++] = arr[t2++];
}
// Let's replace sortedArray values into original array
for( int i = 0; i < sortedArr.length; i++ )
{
arr[low++] = sortedArr[i];
}
return inversionCount;
}
private static void merge( int[] arr, int low, int mid, int high )
{
int t1 = low;
int t2 = mid + 1;
int[] sortedArray = new int[arr.length];
int counter = 0;
while( t1 <= mid && t2 <= high )
{
if( arr[t1] < arr[t2] )
{
sortedArray[counter++] = arr[t1];
t1++;
}
else if( arr[t2] < arr[t1] )
{
sortedArray[counter++] = arr[t2];
t2++;
}
}
while( t1 <= mid )
{
sortedArray[counter++] = arr[t1++];
}
while( t2 <= high )
{
sortedArray[counter++] = arr[t2++];
}
counter = 0;
for( int i = low; i <= high; i++ )
{
arr[i] = sortedArray[counter++];
}
}
}