nested for loop value of not initialized
Clash Royale CLAN TAG#URR8PPP
nested for loop value of not initialized
I know question sounds dumb, I can't really figure out what is wrong in this code?
void sort(int *arr, int size)
int min = 0;
for (int i = 0; i < size - 1; i++)
for (int j = i; i < size; j++)
if (arr[min] > arr[j])
min = j;
if (min != i)
Swap(&arr[i], &arr[min]);
The following code should sort the arr
but it is giving segmentation fault.
I ran this code via debugger and it says the value of j
at line
arr
j
for (int j = i; i < size; j++)
something like 3234
(not initialized) and program ends. But j
should be 0
.
3234
j
0
debuger screenshort
for(int j = i;i<size;j++)
i
2 Answers
2
In your second for
loop, it should be j < size
, not i < size
.
for
j < size
i < size
There are 3 problems in your sort
function:
sort
for
i
j
j
arr
min
i
j
i + 1
Here is a corrected version:
void sort(int *arr, int size)
for (int i = 0; i < size - 1; i++)
int min = i;
for (int j = i + 1; j < size; j++)
if (arr[min] > arr[j])
min = j;
if (min != i)
Swap(&arr[i], &arr[min]);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
In
for(int j = i;i<size;j++)
the value ofi
never changes, so it spins forever..– David C. Rankin
Aug 13 at 2:59