To sort an array there are different methods. And you may be familiar with them. However, what to do if you want to simply check whether an array is sorted or not.

Start from the beginning of the array and compare whether the 0th element is less than 1st element and so on up to the end of the array (for Ascending order). If you can move up to the end of the array without any failure in the condition, then you can assure that the array is sorted.

You can apply the reverse logic of method 1. Initially check whether the 0th element is greater than 1st element. If this condition is true, then you can say it is not sorted without checking further.

Let us see a function using the

Here

__Method 1__Start from the beginning of the array and compare whether the 0th element is less than 1st element and so on up to the end of the array (for Ascending order). If you can move up to the end of the array without any failure in the condition, then you can assure that the array is sorted.

__Method 2__You can apply the reverse logic of method 1. Initially check whether the 0th element is greater than 1st element. If this condition is true, then you can say it is not sorted without checking further.

Let us see a function using the

**second method**to check whether an array is sorted or not.
int issorted(int array[], int len){

int i;

for(i=0;i<len-1;i++)

if (a[i]>a[i+1])

return (0); //Unsorted

return (1); //Sorted

}

int i;

for(i=0;i<len-1;i++)

if (a[i]>a[i+1])

return (0); //Unsorted

return (1); //Sorted

}

Here

**array[]**is the actual array and

**len**is the length of the array. This function returns

**1**if the array is sorted and returns

**0**if it is not sorted.

## No comments:

## Post a Comment