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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
#include <iostream>
#include <stdlib.h>
#include <time.h>
//#include "merge_sort.h"
using namespace std;
char c;
void basicMerge(int anArray[],int first, int mid, int last);
void RECURSIVEMERGESORT (int A[],int n);
void printArray(int[],int);
clock_t begin, stop;
long run_time;
int main()
{
//main program
int maxSize = 20;
int theArray [maxSize];
//int B[maxSize];
cout<<"\nWelcome!!!";
cout<<"\nThis is a test of the mergesort procedure and their running times:";
// <<endl<<"\nPlease enter the size of your array: ";
//cin>>maxSize;
//int first = 0;
//int mid = maxSize/2;
//int last = maxSize-1;
for (int i=0; i<maxSize; i++)
theArray[i] = rand()% 100+1;
printArray(theArray, maxSize);
begin = clock();
RECURSIVEMERGESORT(theArray, maxSize);
stop = clock();
cout<<endl<<"\nMergesort\n";
printArray(theArray, maxSize);
run_time = ((long) (stop - begin)) / CLOCKS_PER_SEC;
cout<<"\nRuntime of the procedure was "<<run_time<<endl;
cout<<"\nPlease press any key and enter to exit: ";
cin>>c;
return 0;
}
void printArray(int anArray[], int size)
{
cout<<"\nThe array elements are now as follows: "<<endl;
for (int i = 0; i<size; i++)
cout<<anArray[i]<<" ";
}
void basicMerge(int anArray[],int first, int mid, int last) {
int f1 = first;
int last1 = mid;
int f2 = mid+1;
int last2 = last;
int temp[last+1];
int index = f1;
for(; (f1<=last1)&&(f2<=last2); index++) {
if(anArray[f2]<anArray[f1]) {
temp[index] = anArray[f2];
f2++; }
else {
temp[index] = anArray[f1];
f1++; }
}// end for
for(; (f1<=last1); f1++, index++)
temp[index] = anArray[f1];
for(; (f2<=last2); f2++, index++)
temp[index] = anArray[f2];
for(index = first; index<=last; index++)
anArray[index] = temp[index];
}// end basicMerge
void RECURSIVEMERGESORT (int A[],int n) {
int first=0;
int last=n-1;
//int temp[n];
if (first<last) {
int mid =(first+last)/2;
int n2 = n-mid;
RECURSIVEMERGESORT (A,mid);
RECURSIVEMERGESORT (A,n2);
basicMerge(A, first, mid, last);
}
}// end RECURSIVEMERGESORT
|