Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
practice-cpp/merge_sort/merge_sort.cc
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
40 lines (33 sloc)
815 Bytes
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
namespace jw { | |
void merge(int numbers[], int low, int mid, int high) { | |
// temp array for holding sorted items | |
int b[high - low - 1]; | |
int i = low; | |
int j = mid + 1; | |
int k = 0; | |
// merge items from list in order | |
while (i <= mid && j <= high) { | |
if (numbers[i] <= numbers[j]) { | |
b[k++] = numbers[i++]; | |
} else { | |
b[k++] = numbers[j++]; | |
} | |
} | |
// copy the remaining items to tmp array | |
while (i <= mid) b[k++] = numbers[i++]; | |
while (j <= high) b[k++] = numbers[j++]; | |
--k; | |
while (k >= 0) { | |
numbers[low + k] = b[k]; | |
--k; | |
} | |
} | |
void merge_sort(int numbers[], int low, int high) { | |
if (low < high) { | |
int mid = (low + high) / 2; | |
merge_sort(numbers, low, mid); | |
merge_sort(numbers, mid + 1, high); | |
merge(numbers, low, mid, high); | |
} | |
} | |
} // namespace jw |