冒泡排序

来源:互联网 发布:mac ppt使用教程 编辑:程序博客网 时间:2024/06/06 12:47
    冒泡排序是邻居的两个数据逐一进行对比交换,如此类推。最小移动次数为0,最大对比次数为n-1,如:最大的的数字就是第一位,则获取最大值时,在对其它数字进行对比时,是不用进行任何数字位置的移动,而需要对所有的其它数字进行对比一次,才可以确定当前这个是否最大值。如此可见,序最好的时间复杂度
 0(n) ,最坏时间复杂度为
 0(n²) ,因此冒泡排序总的平均时间复杂度为
 0(n²) 

实体封装:
public class User    {        /// <summary>        /// 名称        /// </summary>        public string Name { get; set; }        /// <summary>        /// 年龄        /// </summary>        public int Age { get; set; }        /// <summary>        /// 性别        /// </summary>        public string Sex { get; set; }        /// <summary>        /// 手机        /// </summary>        public string Mobile { get; set; }    }

实体排序规则:
<span style="font-size:18px;"> public class UserCompare : IComparer<User>    {        public int Compare(User source, User target)        {            int result = -1;            if (source.Age > target.Age)                result = 1;            if (source.Age == target.Age)                result = 0;            if (source.Age == target.Age)                result = -1;            return result;        }    }</span>

冒泡排序封装:
<span style="font-size:18px;">public class BubbleSort    {        /// <summary>        /// 冒泡排序封装        /// </summary>        /// <typeparam name="T"></typeparam>        /// <param name="data"></param>        /// <param name="comparer"></param>        /// <returns></returns>        public static IList<T> SelectSort<T>(IList<T> data, IComparer<T> comparer)        {            if (null == null || data.Count == 0)                return default(IList<T>);            for (int i = 0; i < data.Count - 1; i++)            {                for (int j = i + 1; j < data.Count; j++)                {                    if (comparer.Compare(data[i], data[j]) > 0)                    {                        var temp = data[i];                        data[i] = data[j];                        data[j] = temp;                    }                }            }            return data;        }    }</span>

对实体进行排序:
<span style="font-size:18px;">public class SortClient    {        public void SortUser()        {            List<User> lstUser = new List<User>();            User zhangsan = new User();            zhangsan.Age = 2;            zhangsan.Name = "张三";            lstUser.Add(zhangsan);            User lisi = new User();            lisi.Age = 5;            lisi.Name = "李四";            lstUser.Add(lisi);            User wangwu = new User();            wangwu.Age = 4;            wangwu.Name = "王五";            lstUser.Add(wangwu);            User zhaoliu = new User();            zhaoliu.Age = 3;            zhaoliu.Name = "赵六";            lstUser.Add(zhaoliu);            IList<User> lstUserSort = BubbleSort.SelectSort<User>(lstUser, new UserCompare());        }    } </span>





0 0
原创粉丝点击