当前位置:编程学习 > C#/ASP.NET >>

C#遍历排序的方法

今天来介绍一下C#中遍历排序的方法,今天就介绍下冒泡法,直接插入法和选择排序法。

1、冒泡法

题目:使用冒泡法对数组中的元素从小到大进行排序。

方法一:

int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
            foreach (int m in arr)
            {
                Console.Write(m + " ");
            }               
            Console.WriteLine();
            int j, temp;
            for (int i = 0; i < arr.Length - 1; i++)
            {
                j = i + 1;
                id:
                if (arr[i] > arr[j])
                {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                    goto id;
                }
                else
                {
                    if (j < arr.Length - 1)
                    {
                        j++;
                        goto id;
                    }
                }
            }
            foreach (int n in arr)
            {
                Console.Write(n + " ");
            }      
            Console.WriteLine();
            Console.ReadLine();

方法二:

            int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
            int i, j, temp;
            bool done = false;
            j = 1;
            while ((j < arr.Length) && (!done))
            {
                done = true;
                for (i = 0; i < arr.Length - j; i++)
                {
                    if (arr[i] > arr[i + 1])
                    {
                        done = false;
                        temp = arr[i];
                        arr[i] = arr[i + 1];
                        arr[i + 1] = temp;
                    }
                }
                j++;

            }
            foreach (int n in arr)
            {
                Console.Write(n + "--");
            }
            Console.WriteLine();
            Console.ReadLine();

2、插入排序法

int[] arr = new int[] { 3, 9, 27, 6, 18, 12, 21, 15 };
            foreach (int n in arr)
                Console.Write("{0}", n + " ");
            Console.WriteLine();
            for (int i = 0; i < 6; ++i)
            {
                int temp = arr[i];
                int j = i;
                while ((j > 0) && (arr[j - 1] > temp))
                {
                    arr[j] = arr[j - 1];
       &nb

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,