当前位置:编程学习 > C#/ASP.NET >>

C#实现所有经典排序算法

1、选择排序

选择排序
class SelectionSorter   
{   
    private int min;   
    public void Sort(int[] arr)   
    {   
        for (int i = 0; i < arr.Length - 1; ++i)   
        {   
            min = i;   
            for (int j = i + 1; j < arr.Length; ++j)   
            {   
                if (arr[j] < arr[min])   
                    min = j;   
            }   
            int t = arr[min];   
            arr[min] = arr[i];   
            arr[i] = t;   
        }   
    }   
    static void Main(string[] args)   
    {   
        int[] array = new int[] { 1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };   
        SelectionSorter s = new SelectionSorter();   
        s.Sort(array);   
        foreach (int m in array)   
            Console.WriteLine("{0}", m);   
    }   
}

2、冒泡排序

冒泡排序
class EbullitionSorter   
{   
    public void Sort(int[] arr)   
    {   
        int i, j, temp;   
        bool done = false;   
        j = 1;   
        while ((j < arr.Length) && (!done))//判断长度   
        {   
            done = true;   
            for (i = 0; i < arr.Length - j; i++)   
            {   
                if (arr[i] > arr[i + 1])   
                {   
                    done = false;   
                    temp = arr[i];   
                    arr[i] = arr[i + 1];//交换数据   
                    arr[i + 1] = temp;   
                }   
            }   
            j++;   
        }   
    }   
  
    static void Main(string[] args)   
    {   
        int[] array = new int[] { 1, 5, 3, 6, 10, 55, 9, 2, 87, 12, 34, 75, 33, 47 };   
        EbullitionSorter e = new EbullitionSorter ();   
        e.Sort(array);   
        foreach (int m in array)   
            Console.WriteLine("{0}", m);   
  
    }   
}

3、快速排序

快速排序
class QuickSorter   
{   
    private void swap(ref int l, ref int r)   
    {   
        int temp;   
        temp = l;   
        l = r;   
        r = temp;   
    }   
    public void Sort(int[] list, int low, int high)   
    {   
        int pivot;//存储分支点   
        int l, r;   
        int mid;   
        if (high <= low)   
            return;   
        else if (high == low + 1)   
        {   
            if (list[low] > list[high])   
                swap(ref list[low], ref list[high]);   
            return;   
        }   
        mid = (low + high) >> 1;   
        pivot = list[mid];   
        swap(ref list[low], ref list[mid]);   
        l = low + 1;   
        r = high;   
        do  
        {   
        while (l <= r

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,