选择排序法

来源:互联网 发布:淘宝美工作品欣赏 编辑:程序博客网 时间:2024/06/13 05:26

#region

/*1.1 选择排序法的伪码描述

 * void SelectionSort(int List[], int N)

 * {

 *  for(i=0; i<n; i++)

 *  {

 *      从List[i]到List[N-1]中找出最小元,并将其位置赋给MinPosition;

 *      将未排序部分的最小元换到有序部分的最后位置

 *  }

 * }

 * 

 */

#endregion

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;


namespace msheng2018082301

{

    classProgram

    {

        static void Main(string[] args)

        {

            //int[] a = { 45, 34, 23, 34, 54, 65, 77, 74, 34, 65, 64 };

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

            a = SelectionSort(a);


            foreach (var bin a)

                Console.Write(b.ToString() + "  ");


            Console.ReadLine();

        }


        //传入一个数组,对其进行选择排序

        static int[] SelectionSort(int[] a)

        {

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

            {

                //找出i到n的最小值的位置

                int minValue = a[i];

                int currentValue= a[i];

                int minPosition = i;


                int tempValue = 0;

                for(int m =i; m < a.Length; m++)//找到剩下的最小值

                {

                    currentValue = a[m];

                    if (minValue >= currentValue)

                    {

                        minValue = currentValue;

                        minPosition = m;                      

                    }

                }

                tempValue = a[i];

                a[i] = minValue;//将该最小值放在已经排序的最后面

                a[minPosition] = tempValue;

            }

            return a;

        }

    }


    /*

     * 总结:

     * 选择性排序分两个部分:

     * 1.已经排好的部分

     * 2.未排好的部分

     * 执行过程需要两个循环

     * 第一个循环 遍历整个数组的所有元素

     * 第二个循环 遍历未排好的那个部分

     * 具体操作分两步

     * 1.从未排序的集合中找出最小值,并记下该值位置

     * 2.取出已经排好序的集合的最后一位元素,将其放到一个临时变量中,为了让最小值与该值进行位置交换,

     * 就相当于从一系列数中取出一个最小值,然后将需要放到地方的那个数也取出来,进行一个交换--这一步非常重要

     */

}


原创粉丝点击