Wednesday 3 September 2014

C Program to check whether an array is sorted or not

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.

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

}

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