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
|
#include <iostream>
using namespace std;
void merge(int arr[], int size, int low, int middle, int high){
int temp[size];
for (int i = 0; i <= high; i++){
temp[i] = arr[i];
}
int i = low;
int j = middle+1;
int k = low;
while (i <= middle && j <= high){
if (temp[i] <= temp[j]){
arr[k] = temp[j];
i++;
}
else{
arr[k] = temp[j];
j++;
}
k++;
}
while(i <= middle){
arr[k] = temp[i];
k++;
i++;
}
}
void mergeSort(int arr[], int size, int low, int high){
if (low < high){
int middle = (low + high) / 2;
mergeSort(arr, size, low, middle);
mergeSort(arr, size, middle+1, high);
merge(arr, size, low, middle, high);
}
}
int main()
{
int arr[5] = {5, 10, 1, 6, 2};
mergeSort(arr, 5, 0, 4);
for (int i = 0; i < 5; i++)
cout << arr[i] << endl;
return 0;
}
|