C#, Beginner Qionglin (03) - the source program to calculate the minimum and maximum values (Min, Max) of an array

Search for the smallest/largest element of an array

Suppose we have an n-element array in which we want to find a minimum (or maximum) element. a is an array with indices from 0 to  n-1  . Its elements will be labeled: a[0], a[1], a[2], a[3], ..., a[n- 1].

To find the smallest element, we will take the following steps:

  • At the beginning, we will initialize the result with the first value in the array, which is a[0],
  • Then we will iterate over the next elements of the array (starting from the second), and if the given element of the array is smaller than our result, we will update our result by assigning this element to it,
  • After iterating over all elements, we will get the smallest element in the array.
     

base code

private void button1_Click(object sender, EventArgs e)
{
    int[] a = { 10, -5, 2, 3, 88, 6, -19, 23 };

    int min = a[0];
    for(int i=1; i<a.Length; i++)
    {
        if (a[i] < min)
        {
            min = a[i];
        }
    }

    int max = a[0];
    for(int i=1; i<a.Length-1; i++)
    {
        if (a[i] > max)
        {
            max = a[i];
        }
    }

    MessageBox.Show("数组最小值 = " + min + "\n最大值 =" + max, "计算数组最大、最小值");
}

Minimalist code

Sort from smallest to largest first.

private void button1_Click(object sender, EventArgs e)
{
    int[] a = { 10, -5, 2, 3, 88, 6, -19, 23 };
    Array.Sort(a);
    MessageBox.Show("数组最小值 = " + a[0] + "\n最大值 =" + a[a.Length-1], "计算数组最大、最小值");
}

The first element is the minimum value; the last element is the maximum value.

speed? Super fast!

What is the median (not mean!)?

int mv = a[a.Length / 2];

Some key points of array sorting

The Array class is an abstract class that is the base class for all arrays. Denoting an array with square brackets creates a new class derived from the Array class that can use the methods and properties defined by the Array class.

 Array has a static method to sort the elements of the array, and the element type must implement the Icompare interface. For simple types (such as int and string types, they have already implemented this interface and can be sorted directly using the sort method).


Overall ascending order: Array.Sort(A);
overall descending order: ascending first, then reverse Array.Reverse(A);
local ascending order: Array.Sort(A,2,4);//Start from the element with index 2 Ascending order of 4 elements
Local descending order: Array.Reverse(A,2,3);//Reverse the 3 elements starting from the element with index 2, which is followed by Array.Sort.
 

Guess you like

Origin blog.csdn.net/beijinghorn/article/details/129892984