0
Any idea why my code adds a new number in that I never entered when sorted?
4 Antworten
+ 12
Remember that when referencing elements in an array you start at 0 for the first element.
So if the size of an array is 5 the last element is stored at position 4
+ 5
You're comparing past the end of the array at line 36, then storing the number past the end at 39 and 40; your loop appears too long at 34:
34: for(int j=0; j<size; j++)
{
36: if(arr[j]>arr[j+1])
{
temp=arr[j];
39: arr[j]=arr[j+1];
40: arr[j+1]=temp;
This works for me:
34: for(int j=0; j<size-1; j++)
+ 5
If you want to prove to yourself that you're getting the number just past the end of the array, add this in sort just before your loops:
cout << arr[5];
The number it prints will be the unexplained inserted number.
+ 1
Thanks