Hello.
I am trying to code a merge sort algoritm, using my knowledge of C++. I have made some code but it is not working. It is giving some random results.
Can you please look at my code and see improvements I can make.
Thanks?
Code:#include <cstdlib> #include <iostream> using namespace std; void print(int *niz) { for (int f1=0; niz[f1]!='\0'; f1++) { cout << niz[f1] << " "; } cout << endl; } void merge(int *niz, int low, int medium, int high) { int *niz2 = new int[high-low]; int bottom = low; int top = medium-1; for (int f1=low; f1<high; f1++) { if(bottom>medium) { niz2[f1-low] = niz[top++]; } else if(top>high) { niz2[f1-low] = niz[bottom++]; } else if(niz[bottom]<niz[top]) { niz2[f1-low] = niz[bottom++]; } else { niz2[f1-low] = niz[top++]; } } for (int f1=low; f1<high; f1++) { niz[f1]=niz2[f1-low]; } delete [] niz2; } void merge_sort(int *niz, int low, int high) { if(low < high) { int middle = (high+low)/2; merge_sort(niz, low, middle); merge_sort(niz, middle+1, high); merge(niz, low, middle, high); } } int main(int argc, char** argv) { srand((unsigned)time(0)); int velicina = 10; int *niz = new int[velicina]; for (int f1=0; f1<velicina; f1++) { niz[f1] = rand()%10+1; } print(niz); merge_sort(niz, 0, velicina-1); print(niz); cout << "kraj" << endl; return 0; }




Reply With Quote
