基本的排序

来源:互联网 发布:摄影师男朋友 知乎 编辑:程序博客网 时间:2024/04/29 22:55

    //冒泡排序
    public class BubbleSorter
    {
        public static void Sort(ref int[] list)
        {
            int temp = 0;
            bool hasdone = false;
            //for可能要多次,一次不能完成所有的排序
            while (!hasdone)
            {
                hasdone = true;
                for (int i = 0; i < list.Length - 1; i++)
                {
                    if (list[i] < list[i + 1])
                    {
                        hasdone = false;
                        temp = list[i];
                        list[i] = list[i + 1];
                        list[i + 1] = temp;
                    }
                }
            }
        }
    }
    //选择排序
    public class SelectSorter
    {
        public static void Sort(ref int[] list)
        {
            int i, j, min, temp;
            for (i = 0; i < list.Length - 1; i++)
            {
                min = i;
                for (j = i + 1; j < list.Length; j++)//这里选出最小数的索引
                {
                    if (list[j] > list[min])
                    {
                        min = j;
                    }
                }
                temp = list[min];//当前最小的数
                list[min] = list[i];//交换
                list[i] = temp;//i的位置放当前最小的
            }
        }
    }
    //插入排序
    public class InsertionSorter
    {
        public static void Sort(ref int[] list)
        {
            int i = 0, temp = 0;
            for (i = 0; i < list.Length - 1; i++)
            {
                temp = list[i];
                int inner = i;
                while (inner > 0 && list[inner - 1] >= temp)
                {
                    list[inner] = list[inner - 1];
                    inner--;
                }
                list[inner] = temp;
            }
        }
    }

原创粉丝点击