C# 中的冒泡排序

        int num;

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

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

            for (int j=i+1; j < arr.Length; j++)
            {

                if (arr[j] > arr[i])
                {

                    num = arr[j];

                    arr[j] = arr[i];

                    arr[i] = num;

                }

            }

        }

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

            Debug.Log(arr[i]);

        }

另一种遍历方式:

     int temp;
        int[] arr = new[] {10, 8, 3, 6, 5, 7, 9};
        for (int j = arr.Length  -1; j > 0; j--)
        {
            for (int i = 0; i < j; i++)
            {
                if (arr[i] > arr[i + 1])
                {
                    temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;                             
                }
            }
        }

 

posted @ 2017-11-24 12:56  U3DEngineer  阅读(184)  评论(0编辑  收藏  举报