冒泡,选择,顺序查找 算法

来源:互联网 发布:网络软件工程师培训 编辑:程序博客网 时间:2024/06/03 09:29
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace LianXi{    class Program    {        static void Main(string[] args)        {            int[] Array = new int[12];            Random r = new Random();            for (int i = 0; i < Array.Length; i++)            {                Array[i] = r.Next(0, 11);                Console.Write(" " + Array[i]);            }            Console.Write('\n');            // BubbleSort(Array);//冒泡调用             // SelectSort(Array);//选择调用           // Console.WriteLine( SequntialSearch(Array,5));//顺序查找                       for (int i = 0; i < Array.Length; i++)            {                Console.Write(" " + Array[i]);            }            Console.Write('\n');            Console.ReadKey();        }        /*         * 选择和冒泡遍历的次数都是n-1,说明交换的次数都是差不多的         * 但是从代码来看,选择的交换次数比冒泡的次数少,也就是说在         * 一定的程度上选择的效率高于冒泡         */        public static void SelectSort(int[] Array)        {            int temp;            int min;            for (int i = 0; i < Array.Length - 1; i++)                /出n-1个最小值            {                min = i;//使用min来记录最小值的索引                for (int j = i + 1; j < Array.Length - 1; j++)                {                    if (Array[j] < Array[min]) min = j;                    //得到min最小值的索引                }                temp = Array[i];                Array[i] = Array[min];                Array[min] = temp;                //使用交换原理,交换两个数,                //将当前最小值放在当前序列的最前端,即第i个元素的位置            }        }        public static int SequntialSearch(int[] Array,int key)         {            int i=0;            for ( i = 0; i < Array.Length; i++)             {                if (Array[i] == key) break;             }            if (i >= Array.Length) return -1;            else return i;        }        public static void BubbleSort(int[] Array)        {            int temp;            for (int i = 0; i < Array.Length; i++)            /出n-1个最大值            {                for (int j = 0; j < Array.Length - 1 - i; j++)                /*                 * 要在n个数中排序,也就将问题转换为在剩下的序列中找到最大值                                 * 将找到的最大值并放在该序列的最后(n-k),k表示                      * 已经找出的最大值数k==(i+1)Array.Length=n;                 */                {                    if (Array[j] >= Array[j + 1])                    /*如果两个数比较,那么大的数一定是在右边的,那么                     * 就有了比较的条件Array[j] >= Array[j+1]                     */                    {                        temp = Array[j + 1];                        Array[j + 1] = Array[j];                        Array[j] = temp;                    }                    //交换两个数的值的                }            }        }    }}

0 0
原创粉丝点击