In the below code i am trying to check if the array is sorted in ascending order using recursion;But have a few doubts:
bool isSorted(int *arr, int size){
if(size == 0 || size == 1){
return true;
}
//compare two adjacent elements and reduce the size
if(arr[0] > arr[1]){
return false;
}
bool ans = isSorted(arr+1, size-1);
return ans;
}
In this case int *arr
is not an array, it's pointer to the some element of the array. And arr[0]
means this element, arr[1]
means next element after *arr
. arr[i] <=> *(arr + i)
. U can easily do something like that: int *p = arr[5];
and now p[0] and arr[5] are the same things. So in the first step arr
looks at the first element and compares first and second. On next step arr
looks at the second element and compares second and third etc. And u have to understand a distance between current element and end of array that's why you decrease size
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.