简体   繁体   中英

Checking if array isSorted using Recursion in c++

In the below code i am trying to check if the array is sorted in ascending order using recursion;But have a few doubts:

  1. I dont understand why we use arr[0] and arr[1] in place of using arr[i] and arr[i+1].
  2. I understand why we would pass arr+1, but why are we reducing the size of array using size-1 ? shouldnt this result in the nth part of the array to be reduced ?
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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM