算法学习笔记之冒泡排序

来源:互联网 发布:php权限管理源代码 编辑:程序博客网 时间:2024/05/16 11:09

原理:相邻的两个元素进行比较,如果左边的大于右边,则互换位置,以此类推

时间复杂度:Θ(n^2)

性能一般,但是算法易懂

C#实现:

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace AlgorithmTest{    class BubbleSort    {        public void Sort (int[] arr)        {            int length = arr.Length;            int i;            bool flag;            for (i = 0; i < length-1; i++)            {                flag = true;                int j;                int temp;                for (j = length -1; j > i; j--)                {                    if (arr[j] < arr[j-1])                    {                        temp = arr[j];                        arr[j] = arr[j-1];                        arr[j-1] = temp;                        flag = false;                    }                }                if (flag)                    break;            }        }    }}


原创粉丝点击