-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-sort.cpp
More file actions
41 lines (32 loc) · 987 Bytes
/
merge-sort.cpp
File metadata and controls
41 lines (32 loc) · 987 Bytes
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
/* MergeSort
* Author: Douglas Canevarollo */
/* An O(nlog(n)) time complexity class sorting algorithm. */
#include <iostream>
#include <vector>
using namespace std;
void merge(vector<int> &array, int left, int middle, int right) {
int i, j, k;
vector<int> temp(static_cast<unsigned int> (right - left));
i = left;
j = middle;
k = 0;
while (i < middle && j < right)
if (array[i] <= array[j])
temp[k++] = array[i++];
else
temp[k++] = array[j++];
while (i < middle)
temp[k++] = array[i++];
while (j < right)
temp[k++] = array[j++];
for (i = 0; i < k; i++)
array[left+i] = temp[i];
}
void mergeSort(vector<int> &array, int left, int right) {
if (left < right-1) {
int middle = (left + right)/2;
mergeSort(array, left, middle);
mergeSort(array, middle, right);
merge(array, left, middle, right);
}
}