Turn the following into working C# code within a single class. The algorithm sho
ID: 3712253 • Letter: T
Question
Turn the following into working C# code within a single class. The algorithm should return the median number within an array.
ALGORITHM Median(A[0..n - 11) // Returns the median value in a given array A of n numbers. if n= 1 then return A[0] else Select(A, 0, Ln/2^, n-1) I/NB: The third argument is rounded down ALGORITHM Select(A[0..n-1], l, m, h) // Returns the value at index m in array slice A[l..h], if the slice // were sorted into nondecreasing order. pos ? Partition(A, l, h) if pos= m then return A[pos] return Select(A, I, m, pos -1) return Select(A, pos 1, m, h) if pos > m then if posExplanation / Answer
//Package
using System;
//Program name
namespace MedianFinding
{
//Class to find median
class median
{
//Median function
public int Median(int[] arr)
{
//Return median value of given array of size n
int n = arr.Length;
if (n == 1)
{
return arr[0];
}
else
{
return Select(arr, 0,n / 2, n - 1);
}
}
//Select function
public int Select(int[] A,int l,int m,int h)
{
//Return value at index m in array slice arr[l...h]
//If the slice were sorted into non decreasing order
int pos = Partition(A, l, h);
if (pos == m)
{
return A[pos];
}
else if (pos > m)
{
return Select(A, l, m, pos - 1);
}
else
{
return Select(A, pos + 1, m, h);
}
}
//Partition algorithm
public int Partition(int[] arr,int l,int h)
{
//partition set a pivot element and sort array
//if less than pivot goes to lower index
//greater than pivot goes to upper index
int pivotVal = arr[l];
int pivotLoc = l;
for(int j = l + 1; j <= h; j++)
{
if (arr[j] < pivotVal)
{
pivotLoc++;
int temp = arr[pivotLoc];
arr[pivotLoc] = arr[j];
arr[j] = temp;
}
else
{
int temp = arr[l];
arr[l] = arr[pivotLoc];
arr[pivotLoc] = temp;
}
}
return pivotLoc;
}
}
//main class
class Program
{
//main method
static void Main(string[] args)
{
//Variable declaration
int[] array;
int size;
String userInput;
//Read array size
Console.Write("Please enter the size of the array:");
userInput = Console.ReadLine();
size = Convert.ToInt32(userInput);
//Initialize array and put data
array = new int[size];
Console.Write("Please enter array elements:");
for(int i = 0; i < size; i++)
{
array[i] = Convert.ToInt32(Console.ReadLine());
}
//Object creation of class median
var t = new median();
//Call the median function to get median
Console.WriteLine(" Median= "+t.Median(array));
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.