Question #42015

Find the smallest number in an array and calculate total no. of comparison operators, assignment operations, and how many times the loop will be executed and total time it will take.

Expert's answer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Q42015
{
class Program
{
static void Main(string[] args)
{
List<long> array = new List<long>();
Random rnd = new Random();
int num =0;
for (int i = 0; i < 10000000; i++)
{
num = rnd.Next(0, Int32.MaxValue);
array.Add(num * (rnd.Next(0, 1000)%2==0?-1:1));
}
Method(array.ToArray());
Console.ReadKey();
}
static long? Method(long[] array)
{
if (array == null) return null;
if(array.Length<1) return null;
DateTime now = DateTime.Now;
long min = array[0];
int k = 0,j=1;

for (int i = 1; i < array.Length; i++,k++)
{
if (array[i] < min)
{
min = array[i];
j++;
}
}
DateTime after = DateTime.Now;
TimeSpan time= after - now;
Console.WriteLine("The smallest number: "+min);
Console.WriteLine("Total time: "+(time.Milliseconds+time.Seconds*1000)+" miliseconds");
Console.WriteLine("Total number of assignment operations: "+(3+k+j));
Console.WriteLine("Total number of comparison operations: " + (2 + k * 2));
Console.WriteLine("The loop was executed: "+ k +" time(s)");
return min;
}
}
}

LATEST TUTORIALS
APPROVED BY CLIENTS