Вот метод, где я сортирую массив и нахожу максимальные, минимальные и средние значения.
public static void selectionSort(double[] _arr, ref double max, ref double min, ref double sum, ref double avg)
{
int min1;
double temp;
Console.WriteLine("\n--Original Array--");
printArray(_arr);
Console.WriteLine("--Selection Sort Process--");
for (int i = 0; i < _arr.Length - 1; i++)//Outter loops goes through all of the objects in the array.
{
min1 = i;//Minimum value is set to the current index that the outer loop is at.
for (int j = i + 1; j < _arr.Length; j++)//Inner loop goes thorough and does the swaps.
{
if (_arr[j] < _arr[min1])//Condition checking of the current state of the array
{
min1 = j;//If the current value is less than arr[min] then make j the new min.
}
}
if (min1 != 1)
{
temp = _arr[i];
_arr[i] = _arr[min1];
_arr[min1] = temp;
}
}
printArray(_arr);//Display final sorted array
for (int i = 0; i < _arr.Length; i++)
{
sum += _arr[i];//adds all the values in the array together and into the sum variable
if (max < _arr[i])//if the i value is greater than the max value
{
max = _arr[i];
}
if (min > _arr[i])//if the Min value is greater than the i value
{
min = _arr[i];//the Min value will become the i value
}
}
avg = sum / _arr.Length;//the variable avg = sum divide by the total number of the array
Console.Write("Maximum value: {0}, Minimum value: {1}, Average value: {2}", max, min, Math.Round(avg, 2));
Console.WriteLine();
}
Вот метод, который предполагает использовать значения из метода selectionsort, чтобы найти номера индексов этихзначения.
public static void linearSearch(double[] _arr, double max, double min, double avg)
{
int index1 = 0;
int index2 = 0;
int index3 = 0;
for (int i = 0; i < _arr.Length; i++)
{
if (_arr[i] == max)
{
index1 = i;
}
if (_arr[i] == min)
{
index2 = i;
}
if (_arr[i] == avg)
{
index3 = i;
}
}
Console.WriteLine("Max index number: {0}, Min index number: {1}, Avg index number: {2}", index1, index2, index3);
}
Я использую функцию ref, которая позволяет методу linearsearch использовать те переменные, которые содержат значения, чтобы он мог найти, где находится их индекс.
static void Main(string[] args)
{
int size = 100;
double[] arr1 = new double[size];
double[] arr2 = new double[size];
double[] arr3 = new double[size];
arr1 = importData();
arr2 = importData();
arr3 = importData();
findMaximum(arr1);
double max = 0d;
double min = arr2[0];
double sum = 0d;
double avg = 0d;
selectionSort(arr2, ref max, ref min, ref sum, ref avg);
linearSearch(arr3, max, min, avg);
Console.ReadLine();
}
Массив, который я использую, взят из txt файла.
public static double[] importData()
{
string[] txt = File.ReadLines(@"c: \Users\9993959\Moisture_Data.txt").ToArray();
double[] arr = txt.Select(Convert.ToDouble).ToArray();
return arr;
}
OUTPUT
по ссылке вы можете видеть, что среднее число 48.04 - это то же число, что и вмассив.Что мне нужно, это номер индекса, где это число находится в массиве.