Good day! I am practicing sorting algorithms in C ++, and came across such a problem:
I create an array of X elements, given the X I enter through the keyboard. All this is done in the main() method.
int length; cout << "How many elements do you want to add? Type here: "; cin >> length; int array[length]; After entering X I fill my array with a long X random numbers. And I bring to the screen:
cout << "Your current array is:\n\n"; for(int i = 0; i < length; i++){ array[i] = rand() % 100; printf("%d ", array[i]); } Well, after that we see not sorted array ..
Next, I create a method that takes in parameters our array with my elements and sorts by the bubble method
void sort(int array[]){ int length, temp, j; length = sizeof(array) / sizeof(*array); bool sort = true; while(sort){ j++; sort = false; for(int i = 0 ; i < length - j; i++){ if (array[i] > array[i+1]){ temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; sort = true; } } } } Well, in the main() method I call this method ..
main(){ //declare array sort(array); //output after sorting } But when I run the program, I see that my array is not sorted .. Where is my error? I know that if in Java to write such an implementation, then it will work .. But as I understood it just now, in C ++ it is necessary differently.