Advertisement
J00ker

Sortare prin interclasare

Nov 13th, 2014
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.32 KB | None | 0 0
  1. #include <iostream>
  2. #include <ctime>
  3. #include <cstdlib>
  4.  
  5. using namespace std;
  6.  
  7. int a[10], n = 10;
  8.  
  9. void Generare()
  10. {
  11. srand(time(0));
  12. for(int i = 1; i <= n; i++)
  13. a[i] = rand() % 10;
  14. }
  15.  
  16. inline void Sch(int &x, int &y)
  17. {
  18. int aux;
  19. if(x > y)
  20. {
  21. aux = x;
  22. x = y;
  23. y = aux;
  24. }
  25. }
  26.  
  27. void Afisare()
  28. {
  29. for(int i = 1; i <= n; i++)
  30. cout << a[i] << " ";
  31. }
  32.  
  33. //Interclaseaza secv. a[st...m] si a[m+1...dr]
  34. void Interclasare(int st, int dr, int m)
  35. {
  36. int i, j, k;
  37. int b[1000];
  38. i = st;
  39. j = m+1;
  40. k = 0;
  41. while(i <= m && j <= dr)
  42. if(a[i] <= a[j]) b[++k] = a[i++];
  43. else b[++k] = a[j++];
  44. while(i <= m)
  45. b[++k] = a[i++];
  46. while(j <= dr)
  47. b[++k] = a[j++];
  48. //Transfer din b[1...k] in a[st...dr]
  49. j = st;
  50. for(i = 1; i <= k; i++)
  51. a[j++] = b[i];
  52. }
  53.  
  54. void MergeSort(int st, int dr)
  55. {
  56. int m;
  57. if(dr-st <= 1) //Intervalul [st..dr] are lungimea egala cu 1 sau 2
  58. Sch(a[st], a[dr]);
  59. else
  60. {
  61. m = (st+dr) / 2;
  62. MergeSort(st, m);
  63. MergeSort(m+1, dr);
  64. Interclasare(st, dr, m);
  65. }
  66. }
  67.  
  68. int main()
  69. {
  70. Generare();
  71. Afisare();
  72. cout << "\n";
  73.  
  74. MergeSort(1, n);
  75. Afisare();
  76. cout << "\n";
  77. return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement