C#实现常用的几种排序算法

preview 


//冒泡排序
void BubbleSort(int[] array, int n)
    {
        for (int i = 0; i < n - 1; i++)
        {
            for (int j = 0; j < n - i - 1; j++)
            {
                if (array[j] > array[j + 1])
                {
                    int temp = 0;
                    temp = array[j + 1];
                    array[j + 1] = array[j];
                    array[j] = temp;
                }
            }
        }

    }

//选择排序
    void SelectSort(int[] array, int n)
    {
        for (int i = 0; i < n - 1; i++)
        {
            int minIndex = i;
            for (int j = i + 1; j < n; j++)
            {
                if (array[minIndex] > array[j])
                {
                    minIndex = j;
                }
            }

            if (minIndex != i)
            {
                int temp = array[minIndex];
                array[minIndex] = array[i];
                array[i] = temp;
            }
        }
    }

//插入排序
    void InsertSoet(int[] array, int n)
    {
        for (int i = 1; i < n; i++)
        {
            int j = i;
            while (j > 0)
            {
                if (array[j] < array[j - 1])
                {
                    int temp;
                    temp = array[j];
                    array[j] = array[j - 1];
                    array[j - 1] = temp;
                    j--;
                }
                else
                {
                    break;
                }
            }
        }
    }


//快速排序
    void QuickSort(int[] array, int firstIndex, int lastIndex)
    {
        if (firstIndex < lastIndex)
        {
            int i = firstIndex;
            int j = lastIndex;
            int keyElement = array[firstIndex];//刚开始的基准值
            while (i < j)
            {
                while ((i < j) && (array[j] >= keyElement))
                {
                    j--;
                }
                if (i < j)  
                {
                    array[i] = array[j];
                    i++;
                }
                    
                while ((i < j) && (array[i] < keyElement))
                {
                    i++;
                }
                if (i < j)
                {
                    array[j] = array[i];
                    j--;
                }
                    
            }
            array[i] = keyElement;
            QuickSort(array, firstIndex, i - 1);
            QuickSort(array, i + 1, lastIndex);
        }
    }

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值