Skip to content

Instantly share code, notes, and snippets.

@LindaLawton
Created March 10, 2017 13:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LindaLawton/cccc3ffcde57803fc9b0af16e5620e97 to your computer and use it in GitHub Desktop.
Save LindaLawton/cccc3ffcde57803fc9b0af16e5620e97 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
namespace CsharpCodeExamples
{
class Program
{
static void Main(string[] args)
{
// Quadratic Complexity the more data you have the more checks it has to make and the more time it will take to run.
// if the data is already sorted then the complexity will be liniar o(n) becouse the loop only has to run once.
// If the data is in the complete wrong order then it will be quadratic o(n2)
Console.WriteLine("Enter length of array. (int)");
int maxNumberOfItems = 10;
var holdPrompt = Console.ReadLine();
var result = int.TryParse(holdPrompt, out maxNumberOfItems);
if (!result)
{
Console.WriteLine("Must be a number. Hit any key to exit.");
Console.ReadLine();
return;
}
int Min = 0;
int Max = 2 * maxNumberOfItems;
Random randNum = new Random();
int[] data = Enumerable
.Repeat(0, maxNumberOfItems)
.Select(i => randNum.Next(Min, Max))
.ToArray();
var checkCnt = 0;
Console.WriteLine(string.Format("Array contains '{0}' items.", data.Length - 1));
var startTimer = DateTime.UtcNow;
for (int n = 1; n < data.Length; n++)
{
for (int i = 0; i < data.Length - n; i++)
{
checkCnt++;
if (data[i] > data[i + 1])
{
var hold = data[i];
data[i] = data[i + 1];
data[i + 1] = hold;
}
}
}
var stopTimer = DateTime.UtcNow;
Console.WriteLine(string.Format("I preformed '{0}' checks", checkCnt));
var executionTime = stopTimer.Subtract(startTimer);
Console.WriteLine(string.Format("Execution time '{0}' minutes '{1}' seconds '{2}' Milliseconds", executionTime.Minutes, executionTime.Seconds, executionTime.Milliseconds));
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment