### Weirdness in simple sorting code

I am working on sorting codes, and planning compare them,.. but i m facing really weird problem, could you please help?

After the insertion sort is done, i m storing the sorted array in a "sorted[]" array (line 62). (to compare later with other algos), but in the for loop, where i m dumping 'elements[]' into 'sorted[]', if i comment out that line, then it shows that the insertion sort works proper, but if i keep it, the 'elements' array i m printing shows that the sorting din't go well.

Is this some kind of optimization problem? i m using xcode.

Thank you very much!

 ``123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113`` ``````#include #include using namespace std; int main(int argc, char **argv){ int n, *numbers, *elements, *sorted, flag = 0; cout << "Enter number of elements to be sorted: " << endl; while(!(cin >> n)){ cout << "Please enter a number!: " << endl; cin.clear(); cin.ignore(1000, '\n'); } cout << "The number you entered is: " << n; numbers = new int(n); elements = new int(n); sorted = new int[n](); srand(time(NULL)); for(int i = 0; i < n; i++){ numbers[i] = rand() % n +1; } cout << "\nThe elements are: " << endl; for(int i = 0; i < n; i++) cout << numbers[i] << '\t'; cout << "\nThese numbers will be sorted by following algorithms:" << endl << "1. Insertion sort" << endl << "2. Selection sort" << endl << "3. Bubble sort" << endl << "4. Merge sort" << endl << "5. Quick sort" << endl; ///////////////////////////////////////////Insertion Sort///////////////////////////////////////////////// for(int i = 0; i < n; i++){ elements[i] = numbers[i]; cout << elements[i] << '\t'; } cout << endl; for(int i = 1; i < n; i++){ for(int j = i; j > 0; j--){ if(elements[j] < elements[j-1]){ int temp = elements[j]; elements[j] = elements[j-1]; elements[j-1] = temp; } else break; } } cout << "Sorted array is: " << endl; for (int i = 0 ; i elements[j]) min = j; } if(min != i){ int temp = elements[min]; elements[min] = elements[i]; elements[i] = temp; } } for(int i = 0; i < n; i++) cout << elements[i] << '\t'; for(int i = 0; i < n; i++) if(elements[i] != sorted[i]){ flag = 1; cout << "\nMismatch occured at i = " << i << " with " << elements[i] << " not equal to " << sorted[i] << endl; } if(flag == 1){ cout << "Sorted elements don't match!" << endl; flag = 0; } else { cout << "Sorted elements match!" << endl; } delete[] numbers; delete[] sorted; delete[] elements; return 0; }``````
Topic archived. No new replies allowed.