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
|
#include <iostream>
using namespace std;
void merge(int* leftHalf, int* rightHalf, int* sorted) {
int leftIndex = 0, rightIndex = 0, sortedIndex = 0;
while(leftIndex < sizeof(leftHalf) && rightIndex < sizeof(rightHalf)) {
if(leftHalf[leftIndex] < rightHalf[rightIndex]) {
sorted[sortedIndex] = leftHalf[leftIndex];
leftIndex++;
}
else {
sorted[sortedIndex] = rightHalf[rightIndex];
rightIndex++;
}
sortedIndex++;
}
while(leftIndex < sizeof(leftHalf)) {
sorted[sortedIndex] = leftHalf[leftIndex];
leftIndex++;
sortedIndex++;
}
while(rightIndex < sizeof(rightHalf)) {
sorted[sortedIndex] = rightHalf[rightIndex];
rightIndex++;
sortedIndex++;
}
}
int* mergeSort(int list[]) {
const int elements = (int)(sizeof(list) / sizeof(list[0]));
const int midpoint = (int)(elements / 2);
if(elements <= 1) {
return list;
}
int leftHalf[midpoint], rightHalf[(elements - midpoint)];
int* leftPtr = leftHalf,* rightPtr = rightHalf;
for(int i = 0; i < midpoint; i++) {
leftHalf[i] = list[i];
}
for(int i = midpoint; i < elements; i++) {
rightHalf[i - midpoint] = list[i];
}
leftPtr = mergeSort(leftPtr);
rightPtr = mergeSort(rightHalf);
int sorted[elements];
merge(leftHalf, rightHalf, sorted);
return list;
}
int main(int argc, char* argv[]) {
int number[] = {2, 3, 4, 2, 5, 8, 2, 19, 3, 6, 2};
int* numberPtr = number;
numberPtr = mergeSort(numberPtr);
cout << "The sorted numbers are: " << "\n";
for(int i = 0; i < sizeof(number) / sizeof(number[0]); i++) {
cout << number[i] << "\n";
}
cin.get();
return 0;
}
|