体验C#——冒泡算法的C#实现

来源:互联网 发布:goldwave mac版 编辑:程序博客网 时间:2024/06/02 05:53

一、冒泡排序的基本流程。                                             

二、C#代码实现

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace T2Array{    class Sort    {        //,冒泡排序算法        public void bubbleSort()        {            //定义一个一维数组            int[] arr = new int[] { 4, 9, 28, 6, 11, 21, 15 };            //没有经过排序的一维数组            Console.WriteLine("原始数组:");            foreach (int m in arr)            {                Console.Write(" {0}",m);            }            Console.WriteLine();            //开始进行冒泡排序            int temp, j;            for (int i = 0; i < arr.Length - 1; i++)            {                j = i + 1;//id:            id:                if (arr[i] < arr[j])                {                    //两者值进行交换                    temp = arr[j];                    arr[j] = arr[i];                    arr[i] = temp;                    goto id;                }                else                {                    //判断还有没有值                    if (j < arr.Length - 1)                    {                        j++;                                 goto id;                    }                }            }            Console.WriteLine("冒泡排序后的数组:");            foreach (int a in arr)            {                                Console.Write(" {0}",a);            }        }    }    class Program    {                static void Main(string[] args)        {            Sort sort = new Sort();            sort.bubbleSort();            Console.ReadKey();        }    }}


0 0
原创粉丝点击