C#練習—冒泡排序和選擇排序

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

namespace ConsoleApplication9
{
    class Program
    {
        static  void Main(string[] args)
        {
            Console.Write("冒泡排序");
            bomble();
            Console.Write("選擇排序");
            Select();
            Console.ReadLine();
        }
        public static void bomble()//冒泡排序
        {
            int[] a = { 12, 3, 5, 13, 11, 4 };
            for (int i = 0; i < a.Length-1 ; i++)
            {
                for (int j = 0; j < a.Length-1; j++)
                {
                    int temp = 0;
                    if (a[j] >a[j + 1])//冒泡排序就是相鄰倆個數之間的比較。的排後面。
                    {
                        temp = a[j+1];
                        a[j + 1] = a[j];
                        a[j] = temp;
                    }
                }
                
            }
            foreach(int  x in a)
            {
                Console.Write(x + " ");
            }
        }

        public static void Select()////選擇排序
        {
            int[] a = { 12, 3, 5, 13, 11, 4 };
            for (int i = 0; i < a.Length - 1; i++)
            {
                int temp = 0;
                int min = a[i];//設置一個數,默認爲最小的數min,這裏我以i=0,a[0]開始
                int minindex = i;//下標爲i;
                for (int j = i+1; j < a.Length ; j++)
                {
                    if (a[minindex] > a[j])//以默認最小的數逐一和她之後的數比較。
                    {
                        temp = a[i];
                        a[i]= a[j];
                        a[j]= temp;
                    }
                }

            }
            foreach (int x in a)
            {
                Console.Write(x + " ");
            }
        }
    }
}

 

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