Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Quick Sort
- int partition(int* niz, int d, int g) {
- int zid = g;
- int ind = d;
- int pom;
- for (int i = d; i < g; i++) {
- if (niz[i] < niz[zid]) {
- pom = niz[i];
- niz[i] = niz[ind];
- niz[ind] = pom;
- ind++;
- }
- }
- pom = niz[ind];
- niz[ind] = niz[zid];
- niz[zid] = pom;
- return ind;
- }
- void quickSort(int* niz, int poc, int kraj) { // Unosi se indeksi niza (pocetak 0 kraj n - 1)
- if (poc >= kraj) return;
- int i = partition(niz, poc, kraj);
- quickSort(niz, poc, i - 1);
- quickSort(niz, i + 1, kraj);
- }
- // Merge Sort
- void merge(int* niz, int L, int D, int* levi, int* desni) {
- int nl = L;
- int nd = D;
- int i = 0, j = 0, k = 0;
- while (i < nl && j < nd) {
- if (levi[i] < desni[j]) {
- niz[k] = levi[i];
- i++;
- }
- else {
- niz[k] = desni[j];
- j++;
- }
- k++;
- }
- while (i < nl) {
- niz[k] = levi[i];
- k++;
- i++;
- }
- while (j < nd) {
- niz[k] = desni[j];
- k++;
- j++;
- }
- }
- void mergeSort(int * niz, int n) {
- if (n < 2)
- return;
- int s = n / 2;
- int *levi = new int[s];
- int *desni = new int[n - s];
- for (int i = 0; i < s; i++) {
- levi[i] = niz[i];
- }
- for (int i = 0; i < n - s; i++) {
- desni[i] = niz[s + i];
- }
- mergeSort(levi, s);
- mergeSort(desni, n - s);
- merge(niz, s, n - s, levi, desni);
- delete[] levi;
- delete[] desni;
- }
- // Binary Search
- int binarySearch(int *niz, int n, int el) {
- int d = 0;
- int g = n - 1;
- int s = (d + g) / 2;
- while (niz[s] != el && s != d && s != g) {
- if (niz[s] > el) {
- g = s - 1;
- }
- else {
- d = s + 1;
- }
- s = (d + g) / 2;
- }
- if (niz[s] == el) return s;
- else return -1;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement