Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Linq;
- using System.Linq.Expressions;
- using System.Runtime.InteropServices;
- namespace ConsoleApp1
- {
- class Question1
- {
- /*
- A function that tells if a given array is sorted by ascending/descending order or not.
- Input: arr - The array we wish to check.
- Output: 1 - sorted by ascending order, 2 - sorted by descending order, 3 - not sorted at all.
- */
- public static int IsArraySorted(int[] arr)
- {
- bool sortedAscending = true, sortedDescending = true;
- int i = 0, returnAnswer = 0; // Variable loop
- for (i = 0; i < arr.Length - 1; i++) // Avoid out of bounds exceptions.
- {
- if (arr[i] < arr[i + 1]) // Not descending, a value ahead is greater
- {
- sortedDescending = false;
- }
- else if (arr[i] > arr[i + 1]) // Not ascending... A value ahead is smaller
- {
- sortedAscending = false;
- }
- }
- // Avoid having multiple return statements:
- if (sortedAscending)
- {
- returnAnswer = 1;
- }
- else if (sortedDescending)
- {
- returnAnswer = 2;
- }
- else
- {
- returnAnswer = 3;
- }
- return returnAnswer;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement