Skip to content

Commit 598f1bf

Browse files
author
Cody Gagnon
committed
mergeSort complete
1 parent 7f14c81 commit 598f1bf

1 file changed

Lines changed: 18 additions & 5 deletions

File tree

‎class_code/11-27-sorting_algorithms/SortingAlgorithms.java‎

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ private void divideInTwoSortAndMerge(int first, int last) {
114114
divideInTwoSortAndMerge(mid + 1, last);
115115
// Merge sorted halves
116116
merge(first, mid, last);
117-
117+
118118
}
119119
// else
120120
// Base case: nothing to do
@@ -131,7 +131,7 @@ private void merge(int first, int mid, int last) {
131131

132132
// Allocate a temp array on the heap
133133
// temp must be big enough to receive the two halves of A
134-
int[] temp = new int[last-first + 1];
134+
int[] temp = new int[last - first + 1];
135135

136136
// Index for temp
137137
int index = 0;
@@ -144,12 +144,25 @@ private void merge(int first, int mid, int last) {
144144
int last2 = last;
145145

146146
// Copy the two halves in temp (in increasing order)
147-
147+
while (first1 <= last1 && first2 <= last2) {
148+
if (a[first1] <= a[first2]) {
149+
temp[index++] = a[first1++];
150+
} else {
151+
temp[index++] = a[first2++];
152+
}
153+
}
148154
// Anything left in the first half
149-
155+
while (first1 <= last1) {
156+
temp[index++] = a[first1++];
157+
}
150158
// Anything left in the second half
151-
159+
while (first2 <= last2) {
160+
temp[index++] = a[first2++];
161+
}
152162
// Copy temp in a
163+
for (int i = 0; i < temp.length; i++) {
164+
a[first + i] = temp[i];
165+
}
153166
}
154167

155168
/**

0 commit comments

Comments
 (0)