C# Basic Syntax - Selection Sort

using System;

 

namespace lesson14_selection sort

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("select sort");

 

            Fundamentals of #region Selection Sort

            //8,7,1,5,4,2,6,3,9

            //Create a middleman

            //Find the extremum (maximum or minimum)

            // put in target position

            // compare n rounds

            #endregion

 

            #region code implementation

            //Realize ascending order and put the big one at the end

            int[] arr = { 8, 7, 1, 5, 4, 2, 6, 3, 9 };

 

            // compare m rounds

            for (int m = 0; m < arr.Length; m++)

            {

                //The first step is to declare a middleman to record the index

                //At the beginning of each round, the first one is the extreme value by default

                int index = 0;

                //the second step

                // compare sequentially

                //The purpose of reducing m is to exclude the numbers that have been placed in the previous round

                for (int n = 1; n < arr.Length-m; n++)

                {

                    //third step

                    //Find the extremum (maximum value)

                    if (arr[index] < arr[n])

                    {

                        index = n;

                    }

                }

                //The fourth step puts the target position

                //length-1-number of rounds

                //If the position of the current extremum is the target position, there is no need to exchange

                if (index != arr.Length - 1 - m)

                {

                    int temp = arr[index];

                    arr[index] = arr[arr.Length - 1 - m];

                    arr[arr.Length - 1 - m] = temp;

                }

            }

 

            for (int i = 0; i < arr.Length; i++)

            {

                Console.Write(arr[i] + " ");

            }

            #endregion

 

            //Summarize

            //basic concept

            //Create a middleman

            // compare sequentially

            //find the extremum

            // put in target position

 

            //Routine writing

            // double loop

            //Number of outer rounds

            //Inner search

            //initial index

            //record extreme value

            //Memory exchange outside the loop

 

        }

    }

}

 

Guess you like

Origin blog.csdn.net/weixin_61541885/article/details/128745081