array

*deleted
Last edited on
1) You have numerous off-by one errors. Replace all size-1, counter-1, etc. with just size, etc.

2) In selection sort, you need to swap elements only after you found smallest in whole subarray: move swap to after inner loop

3) Do not use floats unless you have a good reason. In C++ default floating type is double. All operations are made on doubles. You are just adding complexity of converting floats to double and back.
the size-1 and counter -1 is because the counter is always 1 ahead in the array. If I remove it and lets say the user enters only 5 integers than my sort function sorts the 6th integer which was never entered and produces some garbage number.

But appears moving the swap to after the inner loop fixed it and is working on every test. MiiNiPaa you are the man. I need to understand why moving the swap to after the inner loop worked.
Last edited on
is because the counter is always 1 ahead in the array
It is the way it is supposed to be. It is why you use < and not <=.
Array size: 3
Valid array idices: 0, 1, 2 (3 indices total)
Proper loop:
1
2
for (int i = 0; i < size; ++i)
for (int i = 0; i <  3  ; ++i)


What happens with current code:
Enter integers ('x' to quit): 1 9 2 8 3 7 4 6 5 x

Data as entered:  1 9 2 8 3 7 4 6
Mean: 3.44444
Median: 5
Sorted array:  1 2 3 4 6 7 8 9
(loss of last array element, incorrect mean)

EDIT: It appears you changed code to introduce another off-by one error. In input loop negating previous one.
Still it is a good idea to get rid of -1 everywhere and just decrement counter once. Or increment it after test. Or fall back to your while loop. It was fworking fine if you delete double input.
Last edited on
Topic archived. No new replies allowed.