sorting arrays
i'm making a function trying to organize my array and for some reason i get a weird number, help me plz.
thank you in advance
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
#include <iostream>
#include <stdio.h>
using namespace std;
void floatingSort(int *array,int length)
{
int i,j;
for(i=0;i<10;i++)
{
for(j=0;j<i;j++)
{
if(array[i]>array[j])
{
int temp=array[i]; //swaps the value
array[i]=array[j];
array[j]=temp;
}
}
}
}
int main(int argc, const char * argv[])
{
int array[5] = {3,9,5,10,7};
floatingSort(array, 5);
cout << array[1] << " " << array[2] << " " << array[3] << " " << array[4] << " " << array[5];
return 0;
}
|
output is
You pass 5 numbers into the function but
for(i=0;i<10;i++)
itterates over 10 going out of bounds on array[]
try
for(i=0;i<length;i++)
I see that in your function the following loop is used
for(i=0;i<10;i++)
where condition i < 10 is applied while your array has only 5 elements.
Last edited on
wow i was dumb, thankyou guys for the help.
Topic archived. No new replies allowed.