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
|
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
void merge(vector<int> aVector, int size, int low, int middle, int high){
int temp[size];
for(int i = low; i <= high; i++){
temp[i] = aVector[i];
}
int i = low;
int j = middle+1;
int k = low;
while (i <= middle && j <= high){
if(temp[i] <= temp[j]){
aVector[k] = temp[i];
++i;
}
else {
aVector[k] = temp[j];
++j;
}
++k;
}
while (i <= middle){
aVector[k] = temp[i];
++k;
++i;
}
}
void mergeSort(vector<int> aVector, int size, int low, int high){
if (low < high){
int middle = (low + high) / 2;
mergeSort(aVector, size, low, middle);
mergeSort(aVector, size, middle+1, high);
merge(aVector, size, low, middle, high);
}
}
int main()
{
const int size = 10;
vector<int> aVector;
srand((unsigned)time(NULL));
for (int i = 0; i < 10; i++) {
int b = rand() % 9 + 1;
aVector.push_back(b);
cout << aVector[i] << " ";
mergeSort(aVector, size, 0, 10);
}
return 0;
}
|