I have written this method to check is an array sorted in ascending order.I would be grateful for your reviews.
static void Main(string[] args)
{
int[] arrayToCheck = { 1, 1, 3, 5 ,2, 7};
Console.WriteLine(IsSorted(arrayToCheck));
}
In the first step I setted up "for loop" to check every single array integer is less than integer with index - 1. And then I created Array of booleans which stored all of these conditions (true/false).
static bool IsSorted(int[] array)
{
bool[] checkAscending = new bool[array.Length - 1];
for (int i = 1; i < array.Length; i++)
{
checkAscending[i - 1] = array[i] >= array[i - 1];
}
In the second step in order to assign value of 1 to true and 0 to false conditionI setted up "for loop" nesting if and else condition.
int[] trueToOne = new int[checkAscending.Length];
for (int i = 0; i < checkAscending.Length; i++)
{
if (checkAscending[i] == true)
trueToOne[i] = 1;
else if (checkAscending[i] == false)
trueToOne[i] = 0;
}
In the last step I had to create new method "Add" which takes array of integers
as a parameter and adding every single array character. If result of addition is equal to array trueToOne length that means all condition are true and Array of integers is sorted.
int result = Add(trueToOne);
if (result == trueToOne.Length)
{
return true;
}
else
{
return false;
}
}
And ADD METHOD:
public static int Add(int[] array)
{
int[] sum = new int[array.Length];
for (int i = 1; i < array.Length; i++)
{
sum[0] = array[0];
sum[i] = array[i] + sum[i - 1];
}
return sum[sum.Length - 1];
}
}