Insertion sorting algorithm in C++ -


i creating insertion algorithm sorting in c++. here is:

void mysort2(int a[], const int num_elements) {     int x[num_elements];     bool inserted(false);      x[0] = a[0];      for(int = 1; < num_elements; i++)     {         inserted = false;         for(int j = 0; j < i; j++)         {             if(a[i] < x[j])             {                 inserted = true;                 memmove(x + j + 1, x+j, (num_elements - j - 1)*sizeof(int*));             x[j]=a[i];                 break;             }         }         if(!inserted)         {             x[i] = a[i];         }     }      print(x, num_elements); } 

when tested data set:

int num_elements(7); int a[] = {2, 1, 3, 7, 4, 5, 6}; 

the code works expected, printing 1, 2, 3, 4, 5, 6, 7 however, when make input bigger 7, program has segmentation error , dumps core. have tried data sets smaller 7 elements , again works expected.

do need using dynamically allocated memory, or there , error in algorithm?

thanks!

sizeof(int*) may not equal sizeof(int). whether or not, meant write sizeof(int). may moving data , stomping on random memory.

oh , fun here's suboptimal (but little code!) insertion sort:

for(auto = first; != last; ++i)     std::rotate(std::upper_bound(first, i, *i), i, std::next(i)); 

Popular posts from this blog