// Faan Tone Liu , demo program for comp 1672, winter 2003 // merge sort #include #include using namespace std; void merge_sort(int *a, int len); void merge(int *dest, int *list1, int len1, int *list2, int len2); // read elements of an array in from a file. Sort them. // Get search key from user, search for it in array. int main() { const int maxarrlen(100); const int maxnamelen(80); char filename[maxnamelen]; ifstream listfile; int arr[maxarrlen]; int numelements(0); int i; cout << "Enter file name containing list (no more than 100 elements): "; cin >> filename; listfile.open(filename, ios::in); // open input file if (!listfile.is_open()) { cout << "Unable to open file." << endl; return 1; } // read the list from the file into the array while (listfile >> arr[numelements]) numelements = numelements + 1; cout << "Before sorting: "; for (i=0; i < numelements; i++) cout << arr[i] << " "; cout << endl; //sort it merge_sort(arr, numelements); cout << "After sorting: "; for (i=0; i < numelements; i++) cout << arr[i] << " "; cout << endl; return 0; } // sort the array a in increasing order, with merge sort // a pointer to the beginning of the array, and the length of the array // are passed as parameters void merge_sort(int *a, int len) { if (len == 1) return; merge_sort(a, len/2); merge_sort(a+len/2, len-len/2); merge(a, a, len/2, a+len/2, len-len/2); } // merge list1 and list2 together and store in dest. Note that // list1 and list2 might occupy the same space in memory, so we // need a scratch copy. The values in the sub-lists may be wiped out. void merge(int *dest, int *list1, int len1, int *list2, int len2) { int *scratch = new int[len1+len2]; int pos1(0), pos2(0), i; for (i=0; i < len1+len2; i++) { if (pos2==len2 || (pos1 < len1 && list1[pos1] < list2[pos2])) scratch[i] = list1[pos1++]; else scratch[i] = list2[pos2++]; } for (i=0; i < len1+len2; i++) dest[i] = scratch[i]; delete scratch; }