An array that reads 10 values entered into it and returns them in ascending order. For years people have struggled to come up with a solution to this without resorting to a ready made solution like quick sort. The simplest form of this algorithm is shown below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
int[] Array = new int[5];
int temp;
Console.WriteLine("type in 5 values");
for (int i=0; i<5; i++)
{
Array[i] = int.Parse(Console.ReadLine());
}
//so far we've seen the easy part, the one where you just have to follow the syntax of the //programming language.
for (int i = 0; i < Array.Length - 1; i++)
{
for (int j = i + 1; j < Array.Length; j++)
{
if (Array[i] > Array[j])
{
//the first for loop cycles through the array up to to the position prior to last.
// the second for loop runs through t he whole length of the array starting at index 1 rather than 0. a //temp var holds the greater value between the two compared values in the if statement.
//the array will then at position [i] get the value of [j], which is one space ahead of [i], while
//[j] receives the value of the temp var, which stores the value from the relational operation >
temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
}
}
Console.Write("Sorted:");
foreach (int sort in Array)
Console.Write("{0} ", sort);
Console.ReadKey();
//in foreach, you don't need to know the length of the array. by setting a variable of the integer type,
// you can display all integer values from the array.
}
}
}
No comments:
Post a Comment