fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. template<class T>
  6. void Merge(const T *iniList, T *mergedList,const int l, const int m, const int n) {
  7. int pos1 = l, posf = l, pos2 = m+1;
  8.  
  9. for (;pos1<=m&&pos2<=n;posf++) {
  10. if (iniList[pos1] < iniList[pos2]) {
  11. mergedList[posf] = iniList[pos1];
  12. pos1++;
  13. }
  14. else {
  15. mergedList[posf] = iniList[pos2];
  16. pos2++;
  17. }
  18. }
  19.  
  20.  
  21. if (pos1 <= m)
  22. for (; pos1 <= m; pos1++,posf++)
  23. mergedList[posf] = iniList[pos1];
  24.  
  25.  
  26. if (pos2 <= n)
  27. for (; pos2 <= n; pos2++, posf++)
  28. mergedList[posf] = iniList[pos2];
  29.  
  30. }
  31. template<class T>
  32. T* MergeSort(T *iniList, const int n) {
  33. T *tempList = new T[n];
  34. for (int s = 1; s < n; s = s * 2) {
  35. int i = 0;
  36. for (; i < n - 2*s + 1; i = i + 2*s)
  37. Merge<T>(iniList, tempList, i, i + s - 1, i + 2*s - 1);
  38.  
  39. iniList = tempList;
  40.  
  41. for (int j = 0; j < n; j++)
  42. cout << iniList[j] << ',';
  43. cout << endl;
  44. system("PAUSE");
  45.  
  46. if ((i + s - 1) < n) Merge<T>(iniList, tempList, i, i + s - 1, n);
  47. else {
  48. for (; i < n; i++)
  49. tempList[i] = iniList[i];
  50. }
  51. }
  52. return tempList;
  53. }
  54. // main function
  55. int main(){
  56. int a[10] = { 26,5,77,1,61,11,59,15,48,19};
  57. int *n= MergeSort<int>(a, 10);
  58. system("PAUSE");
  59. }
Success #stdin #stdout #stderr 0s 3468KB
stdin
Standard input is empty
stdout
5,26,1,77,11,61,15,59,19,48,
1,1,1,77,11,15,15,59,19,48,
1,1,1,11,11,15,15,59,0,0,
1,1,1,11,11,15,15,59,0,0,
stderr
sh: 1: PAUSE: not found
sh: 1: PAUSE: not found
sh: 1: PAUSE: not found
sh: 1: PAUSE: not found
sh: 1: PAUSE: not found