Sort

 

--heap sort . O(n*logn).  auxiliary space O(1).  Unstable sorting.

 class ArraySort

    {

        static void Main(string[] args)

        {

            //give up 0 index. get/set from 1 so that getting right index when do j=2*i.

            int[] a = new int[11] {0,5,77,1,61,11,59,15,48,47,25 };





            ArraySort arrs = new ArraySort();

            arrs.HeapSort(a,a.Length-1);



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

            {

                Console.Write(a[i]);

                Console.Write(",");

            }



            Console.Read();

        }





        void HeapSort(int[] K, int n)

        {

            int i, temp;

            for (i  = n/2; i >=1; i--)

            {

                Adjust(K, i, n);

            }

            for (i = n-1; i >=1; i--)

            {

                temp = K[i + 1];

                K[i + 1] = K[1];

                K[1] = temp;

                Adjust(K, 1, i);

            }

        }



        void Adjust(int[] K, int i, int n)

        {

            int j = 0;

            int temp = K[i];

            j = 2 * i;

            while (j<=n)

            {

                //get max child.

                if (j<n&&K[j]<K[j+1])

                {

                    j++;

                }

                if (temp >=K[j])

                {

                    break;

                }

                K[j / 2] = K[j];

                j = 2 * j;

            }

            K[j / 2] = temp;

        }

    }

  

 

你可能感兴趣的:(sort)