Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <ctime>
- #include <cstdlib>
- using namespace std;
- int a[10], n = 10;
- void Generare()
- {
- srand(time(0));
- for(int i = 1; i <= n; i++)
- a[i] = rand() % 10;
- }
- inline void Sch(int &x, int &y)
- {
- int aux;
- if(x > y)
- {
- aux = x;
- x = y;
- y = aux;
- }
- }
- void Afisare()
- {
- for(int i = 1; i <= n; i++)
- cout << a[i] << " ";
- }
- //Interclaseaza secv. a[st...m] si a[m+1...dr]
- void Interclasare(int st, int dr, int m)
- {
- int i, j, k;
- int b[1000];
- i = st;
- j = m+1;
- k = 0;
- while(i <= m && j <= dr)
- if(a[i] <= a[j]) b[++k] = a[i++];
- else b[++k] = a[j++];
- while(i <= m)
- b[++k] = a[i++];
- while(j <= dr)
- b[++k] = a[j++];
- //Transfer din b[1...k] in a[st...dr]
- j = st;
- for(i = 1; i <= k; i++)
- a[j++] = b[i];
- }
- void MergeSort(int st, int dr)
- {
- int m;
- if(dr-st <= 1) //Intervalul [st..dr] are lungimea egala cu 1 sau 2
- Sch(a[st], a[dr]);
- else
- {
- m = (st+dr) / 2;
- MergeSort(st, m);
- MergeSort(m+1, dr);
- Interclasare(st, dr, m);
- }
- }
- int main()
- {
- Generare();
- Afisare();
- cout << "\n";
- MergeSort(1, n);
- Afisare();
- cout << "\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement