冒泡排序的二种写法

第一种:一个Do……While 加一个For 循环

public static void Sort(ref int[] sortArray)

        {

            bool swapped = true;

            do

            {

                swapped = false;

                for (int i = 0; i < sortArray.Length - 1; i++)

                {

                    if (sortArray[i]>sortArray[i+1])

                    {

                        int temp = sortArray[i];

                        sortArray[i] = sortArray[i + 1];

                        sortArray[i + 1] = temp;

                        swapped = true;

                    }                   

                }

            } while (swapped);

        }

-----------------------------------------------------------------------------------------------------------------------------

第二种:二个For循环

public static void SortFor( ref int[] sortArray)

        {

            for (int i = 0; i < sortArray.Length-1; i++)

            {

                for (int j = 0; j < sortArray.Length-i-1; j++)

                {

                    if (sortArray[j]>sortArray[j+1])

                    {

                        int temp = sortArray[j];

                        sortArray[j] = sortArray[j + 1];

                        sortArray[j + 1] = temp;

                    }

                }

            }

        }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。