Selection Sort 選擇排序 (C#)

using System;

namespace ConsoleApp1
{
    class BubbleSort
    {
        static void Main(string[] args)
        {


            int[] list = { 5, 3, 7, 11, 6, 10, 2, 4, 1 };
            //int[] list = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
            //int[] list = { 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
            //bubbleSortMethod( list );
            selectionSortMethod( list );



            Console.ReadKey();
        }


        static void selectionSortMethod( int[] sortList )
        {
            int temp = 0;
            int exchangeCnt = 0;
            int exchangeIndex = 0;
            int startLenth = 0;
            do
            {
                Console.WriteLine( "startLenth:{0}", startLenth );
                Console.WriteLine( "------------------------------------------------" );
                for ( int i = 0; i < sortList.Length; i++ )
                {
                    Console.WriteLine( sortList[ i ].ToString() );
                }
                Console.WriteLine( "------------------------------------------------" );



                exchangeIndex = 0;
                exchangeCnt = 0;

                temp = sortList[ startLenth ];

                for ( int i = startLenth; i < sortList.Length - 1; i++ )
                {
                    if ( sortList[ i + 1 ] < temp )
                    {

                        temp = sortList[ i + 1 ];
                        exchangeIndex = i + 1;
                        exchangeCnt += 1;
                    }
                }

                if ( exchangeCnt > 0 )
                {
                    sortList[ exchangeIndex ] = sortList[ startLenth ];
                    sortList[ startLenth ] = temp;
                    
                }

                startLenth += 1;


            } while ( startLenth < sortList.Length - 1 );

            Console.WriteLine( "------------------------------------------------" );
            Console.WriteLine( "The final sortList is :" );

            for ( int i = 0; i < sortList.Length; i++ )
            {
                Console.WriteLine( sortList[ i ].ToString() );
            }

            return;
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章