Advertisement
Guest User

Question1

a guest
Feb 28th, 2020
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.49 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4. using System.Runtime.InteropServices;
  5.  
  6. namespace ConsoleApp1
  7. {
  8.     class Question1
  9.     {
  10.         /*
  11.             A function that tells if a given array is sorted by ascending/descending order or not.
  12.             Input: arr - The array we wish to check.
  13.             Output: 1 - sorted by ascending order, 2 - sorted by descending order, 3 - not sorted at all.
  14.          */
  15.  
  16.         public static int IsArraySorted(int[] arr)
  17.         {
  18.             bool sortedAscending = true, sortedDescending = true;
  19.             int i = 0, returnAnswer = 0; // Variable loop
  20.  
  21.             for (i = 0; i < arr.Length - 1; i++) // Avoid out of bounds exceptions.
  22.             {
  23.                 if (arr[i] < arr[i + 1]) // Not descending, a value ahead is greater
  24.                 {
  25.                     sortedDescending = false;
  26.                 }
  27.                 else if (arr[i] > arr[i + 1]) // Not ascending... A value ahead is smaller
  28.                 {
  29.                     sortedAscending = false;
  30.                 }
  31.             }
  32.            
  33.             // Avoid having multiple return statements:
  34.  
  35.             if (sortedAscending)
  36.             {
  37.                 returnAnswer = 1;
  38.             }
  39.             else if (sortedDescending)
  40.             {
  41.                 returnAnswer = 2;
  42.             }
  43.             else
  44.             {
  45.                 returnAnswer = 3;
  46.             }
  47.            
  48.             return returnAnswer;
  49.         }
  50.     }
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement