C#数据结构与算法—排序算法

本文详细介绍了C#中常见的几种排序算法,包括冒泡排序、选择排序、插入排序、归并排序和快速排序。通过对每种算法的原理和实现方法的讲解,分析了它们的时间复杂度和适用场景。例如,冒泡排序和选择排序的时间复杂度相同,但选择排序相对更快;插入排序在处理有序数组时效率较高;归并排序以O(nlogn)的时间复杂度优于O(n2)的排序算法,但空间复杂度较高;快速排序在一般情况下表现优秀,但特殊情况可能退化为O(n2)。
摘要由CSDN通过智能技术生成

冒泡排序

不断对相邻两个元素进行比较并交换位置,有几个元素则需要重复进行几次冒泡操作
冒泡排序的方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sorting
{
   
    class BubbleSort
    {
   
        public static void Sort(int[] arr)
        {
   
            int n = arr.Length;
            for(int i=0;i<n;i++)//重复次数
            {
   
                //减去i 不需要对已经排好序的元素再次进行比较
                for(int j=0;j<n-1-i;j++)//冒泡操作
                {
   
                    if(arr[j]>arr[j+1])
                    {
   
                        Swap(arr, j, j + 1);
                    }
                }
            }
        }
        private static void Swap(int[]arr,int i,int j)
        {
   
            int t = arr[i];
            arr[i] = arr[j];
            arr[j] = t;
        }
    }
}

主函数调用

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sorting
{
   
    class Program
    {
   
        static void Main(string[] args)
        {
   
            int[] a = {
    4, 3, 5, 2, 1, 0 };
            BubbleSort.Sort(a);
            for (int i = 0; i < a.Length; i++)
                Console.Write(a[i]+"\t");

            Console.ReadLine();
        }
    }
}

结果:

0       1       2       3       4       5

冒泡排序支持泛型

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Sorting
{
   
    class BubbleSortGeneric
    {
   
        public static void Sort<E>(E []arr) where E:IComparable<E>
        {
   
            int n = arr.Length;
            for (int i = 0; i < n; i++)//重复次数
            {
   
                //减去i 不需要对已经排好序的元素再次进行比较
                for (int j = 0; j < n - 1 - i; j++)//冒泡操作
                {
   
                    if (arr[j].CompareTo(arr[j + 1])>0)
                    {
   
                        Swap(arr, j, j + 1);
                    }
                }
            }
        }
        private static void Swap<E>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值