Advertisement
J00ker

Untitled

Feb 19th, 2015
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.52 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include <cstdlib>
  5.  
  6. using namespace std;
  7.  
  8. struct Tablou
  9. {
  10. int t[1001];
  11. int n;
  12.  
  13. /*
  14. Construieste un tablou cu lungime n care
  15. memoreaza peste tot valoarea val.
  16. */
  17.  
  18. void Init(int dim, int val)
  19. {
  20. n = dim;
  21. for(int i = 0; i < n; i++)
  22. t[i] = val;
  23. }
  24.  
  25. void Init(int dim)
  26. {
  27. srand(time(0));
  28. n = dim;
  29. for(int i = 0; i < n; i++)
  30. t[i] = rand() % 100;
  31. }
  32.  
  33. void Afisare()
  34. {
  35. for(int i = 0; i < n; i++)
  36. cout << t[i] << " ";
  37. cout << "\n";
  38. }
  39.  
  40. /*
  41. Cauta x in t si returneaza pozitia unde s-a gasit,
  42. sau -1 daca nu apare
  43. */
  44. int Cauta(int x)
  45. {
  46. for(int i = 0; i < n; i++)
  47. if(t[i] == x) return i;
  48. return -1;
  49. }
  50.  
  51. void Insereaza(int p, int x)
  52. {
  53. if(p >= n) p = n;
  54. if(p < 0) p = 0;
  55. for(int i = n; i > p; i++)
  56. t[i] = t[i-1];
  57. t[p] = x;
  58. n++;
  59. }
  60.  
  61. void Sterge(int p)
  62. {
  63. if(p >= n) return;
  64. if(p < 0) p = 0;
  65. for(int i = p; i < n; i++)
  66. t[i] = t[i+1];
  67. n--;
  68. }
  69.  
  70. void QuickSort(int st, int dr)
  71. {
  72. int i, j, piv;
  73. piv = t[st];
  74. i = st+1;
  75. j = dr;
  76. while(i <= j)
  77. {
  78. if(t[i] <= piv) i++;
  79. if(t[j] >= piv) j--;
  80. if(i < j && t[i] > piv && t[j] < piv)
  81. {
  82. swap(t[i], t[j]);
  83. i++; j--;
  84. }
  85. }
  86. swap(t[st], t[i-1]);
  87.  
  88. int m;
  89. m = i-1;
  90. if(st < m-1) QuickSort(st, m-1);
  91. if(m+1 < dr) QuickSort(m+1, dr);
  92. }
  93.  
  94. void Sortare()
  95. {
  96. QuickSort(0, n-1);
  97. }
  98.  
  99. void InserareCresc(int x)
  100. {
  101. Sortare();
  102. for(int i = 0; i < n; i++)
  103. if((x >= t[i]) && (x <= t[i+1]))
  104. {
  105. Insereaza(i, x);
  106. return;
  107. }
  108.  
  109. }
  110. };
  111.  
  112. int main()
  113. {
  114. Tablou a, b;
  115. //a.Init(20, 1);
  116. b.Init(10);
  117. //a.Afisare();
  118. b.Afisare();
  119.  
  120. //cout << "\n" << b.Cauta(27);
  121.  
  122. /*
  123. b.Insereaza(1, 29);
  124. cout << "\n";
  125. b.Afisare();
  126. */
  127.  
  128. /*
  129. b.Sterge(5);
  130. cout << "\n";
  131. b.Afisare();
  132. */
  133.  
  134. /*
  135. b.Sortare();
  136. cout << "\n";
  137. b.Afisare();
  138. */
  139.  
  140. b.InserareCresc(21);
  141. cout << "\n";
  142. b.Afisare();
  143. return 0;
  144. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement