Is it sorted programming exercise.
There ware once a wise mathematician. He very much liked his numbers sorted. And he needs your help:
Write a function that checks if an array of integers is sorted in ascending or descending order.
Example: 123 => True 132 => False 321 => True
Scroll down for the solution of this coding problem.
public static bool isSorted(int[] x) { //the plan is to make one more array, //sort it and check if the elements of //the two arrays are equal. So lets declare an array int[] a = new int[x.Length]; for (int i = 0; i < a.Length; i++) { a[i] = x[i]; } //We can sort it with the Array.Sort() function //Array.Sort() is sorting an array in an //ascending order. Array.Sort(a); bool ascending = true; bool descending = true; //now we will go through each item //in the array x and array a and check if the //two corresponding element are equal using //the != operator. This operator returns true //if the two items checked are Not equal //so if our case if the elements are not //equal will save that result. for (int i = 0; i < x.Length; i++) { if (x[i]!=a[i]) ascending = false; } //then we will do the same but for a descending //ordered array. Array.Reverse(a); for (int i = 0; i < x.Length; i++) { if (x[i] != a[i]) descending = false; } //Now if the array is not in ascending order AND (&&) the array //is not in descending order we will know that the array //is not sorted. if (ascending==false && descending == false) { return false; } return true; //p.s //Why the name of this function is "isSorted" and not //"isItSorted"? Well its about how we using it. Lets imagine a //scenario when we use the function. Something like: //if(isSorted)..... //if(isItSorted)..... //The first sounds better, right ? }