C#對數組排序,Array.sort以及冒泡法

Array.sort

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            string[] strArray = str.Split(' ');
            int[] numArray = new int[strArray.Length];
            for (int i = 0; i< strArray.Length; i++)
            {
                int temp = Convert.ToInt32(strArray[i]);
                numArray[i] = temp;
            }
            Array.Sort(numArray);
            for (int i = 0; i < numArray.Length; i++)
            {
                Console.Write(numArray[i] + " ");
            }
            Console.ReadKey();
        }
    }
}
冒泡法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = Console.ReadLine();
            string[] strArray = str.Split(' ');
            int[] numArray = new int[strArray.Length];
            for (int i = 0; i< strArray.Length; i++)
            {
                int temp = Convert.ToInt32(strArray[i]);
                numArray[i] = temp;
            }
            for(int j = 1; j < str.Length - 1; j++)
            {
                for (int i = 0; i < numArray.Length - 1; i++)
                {
                    if (numArray[i + 1] < numArray[i])
                    {
                        int temp = numArray[i];
                        numArray[i] = numArray[i + 1];
                        numArray[i + 1] = temp;
                    }
                }
            }
           for(int i = 0; i < numArray.Length; i++)
            {
                Console.Write(numArray[i] + " ");
            }
            Console.ReadKey();
        }
    }
}





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