c - Check sorting of an array -
i'm trying write code can check whether dynamic array sorted, error. code has recursive.
when input unsorted array there seems no problem, when input sorted array program halts abruptly with:
process return -1073741571
here code:
#include <stdio.h> #include <stdlib.h> int ordenado(int*); int main() { int = 0, res = 0; int*arr = null; arr = (int*) malloc(sizeof (int)); while (arr[i] != 0) { i++; arr = (int*) realloc(arr, (i + 1) * sizeof (int)); scanf("%d", &arr[i]); } res = ordenado(arr); printf("\n%d ", res); return 0; } int ordenado(int* arr) { if (arr[0] == 0) { return 1; } if (arr[0] <= arr[1]) { return ordenado(arr++); } else return 0; }
sorry first answer not right. corrected below.
explanation
- i added
scanf("%d", &arr[i]);
before loop fillarr[0]
- i changed
ordenado
function- when hit
0
return 1
- when hit
x
next element0
return 1
(note||
short circuit. if don't hit0
there next element. can check0
here too.) - as 2 numbers not in order
return 0
(i think that's faster) - otherwise there next element
not 0
, callordenado(++arr)
(prefix, not postfix)
- when hit
note prefix , postfix:
the difference between prefix , postfix in many programming languages execution order. assume i
, j
being 0
before execution in both statements.
i += ++j;
the above code equivalent this
j = j + 1; = + j;
while below code
i += j++;
is equivalent this
i = + j; j = j + 1;
i.e. in prefix increment takes place before expression evaluated, while in postfix increment takes place after expression evaluated. holds true not matter data type (i.e. includes pointer).
your line of code
return ordenado(arr++);
is equivalent with
return ordenado(arr); a++;
which leads infinite number of function calls @bluepixy pointed out.
corrected code
#include <stdio.h> #include <stdlib.h> int ordenado(int*); int main() { int = 0, res = 0; int* arr = null; arr = (int*) malloc(sizeof (int)); scanf("%d", &arr[i]); while (arr[i] != 0) { i++; arr = (int*) realloc(arr, (i + 1) * sizeof (int)); scanf("%d", &arr[i]); } res = ordenado(arr); printf("\n%d ", res); return 0; } int ordenado(int* arr) { if (arr[0] == 0 || arr[1] == 0) return 1; if (arr[0] > arr[1]) return 0; else return ordenado(++arr); }
example inputs , outputs:
input: 0 output: 1
input: 1 newline 0 output: 1
input: 1 newline 2 newline 3 newline 0 output: 1
input: 2 newline 1 newline 0 output: 0
input: 1 newline 2 newline 3 newline 2 newline 3 newline 0 output: 0
Comments
Post a Comment