vakho

MergeSort

Oct 6th, 2015
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.61 KB | None | 0 0
  1. #include <iostream>
  2. #include <time.h>
  3.  
  4. #define SIZE 3000000 // 30 million
  5.  
  6. using namespace std;
  7.  
  8. void Merge(int* L, int leftSize, int* R, int rightSize, int* A, int aSize) {
  9.     int i, j, k;
  10.     i = j = k = 0;
  11.     while (i < leftSize && j < rightSize) {
  12.         if (L[i] <= R[j]) {
  13.             A[k] = L[i];
  14.             i++;
  15.         } else {
  16.             A[k] = R[j];
  17.             j++;
  18.         }
  19.         k++;
  20.     }
  21.     while (i < leftSize) {
  22.         A[k] = L[i];
  23.         i++;
  24.         k++;
  25.     }
  26.     while (j < rightSize) {
  27.         A[k] = R[j];
  28.         j++;
  29.         k++;
  30.     }
  31. }
  32.  
  33. void MergeSort(int* A, int aSize) {
  34.     if (aSize < 2)
  35.         return;
  36.     int mid = aSize / 2;
  37.     int leftSize = mid;
  38.     int rightSize = aSize - mid;
  39.     int* L = new int[leftSize];
  40.     int* R = new int[rightSize];
  41.     for (int i = 0; i < leftSize; i++) {
  42.         L[i] = A[i];
  43.     }
  44.     for (int i = 0; i < rightSize; i++) {
  45.         R[i] = A[mid + i];
  46.     }
  47.     MergeSort(L, leftSize);
  48.     MergeSort(R, rightSize);
  49.     Merge(L, leftSize, R, rightSize, A, aSize);
  50. }
  51.  
  52. int main() {
  53.  
  54.     system("COLOR F0");
  55.  
  56.     srand(time(NULL));
  57.  
  58.     int* A = new int[SIZE];
  59.     int min = -2;
  60.     int max = 10;
  61.  
  62.     for (int i = 0; i < SIZE; i++) {
  63.         A[i] = rand() % (max - min + 1) + min;
  64.     }
  65.  
  66.     // Print unsorted list...
  67.     /*for (int i = 0; i < SIZE; i++) {
  68.         cout << A[i];
  69.         if (i == SIZE - 1) {
  70.             cout << "." << endl;
  71.         }
  72.         cout << ", ";
  73.     }
  74.     cout << endl;*/
  75.  
  76.     const clock_t begin_time = clock();
  77.     MergeSort(A, SIZE);
  78.     cout << float(clock() - begin_time) / CLOCKS_PER_SEC << " seconds." << endl;
  79.  
  80.     // Print sorted list...
  81.     /*for (int i = 0; i < SIZE; i++) {
  82.         cout << A[i];
  83.         if (i == SIZE - 1) {
  84.             cout << "." << endl;
  85.         }
  86.         cout << ", ";
  87.     }
  88.     cout << endl;*/
  89.  
  90.     system("PAUSE");
  91.     return 0;
  92. }
Advertisement
Add Comment
Please, Sign In to add comment