转C#冒泡排序

 

C#冒泡排序

2011-08-18 11:14 by 陆敏技, 424 visits, 收藏, 编辑

1:原理

以此比较相邻的两个元素,每次比较完毕最大的一个字跑到本轮的末尾。
目的:按从小到大排序。
方法:
假设存在数组:72, 54, 59, 30, 31, 78, 2, 77, 82, 72
第一轮比较相邻两个元素,如果左边元素大于右边元素,则交换。
72和54比较的结果就是,54在前,72在后;
然后72和59比较的结果,59在前,72在后;
以此类推,第一轮比较之后的结果是:54, 59, 30, 31, 72, 2, 77, 78, 72, 82
经过第一轮比较,最大的元素跑到了最后一个,所以第二轮比较,最后一个元素不需要进行比较了。 
第二轮还是从索引0和1开始比较,只是不许要比较最后一个了,算法还是一样的。第三轮、第四轮以此类推。
排序之后的结果:2, 30, 31, 54, 59, 72, 72, 77, 78, 82
2:代码

static List<int> list = new List<int>() { 72, 54, 59, 30, 31, 78, 2, 77, 82, 72 };
      
static void Main(string[] args)
{
    Bubble();
    PrintList();
}
 
static void Bubble()
{
    int temp = 0;
    for (int i = list.Count; i > 0; i--)
    {
        for (int j = 0; j < i - 1; j++)
        {
            if (list[j] > list[j + 1])
            {
                temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            }
        }
        PrintList();
    }
}
 
private static void PrintList()
{
    foreach (var item in list)
    {
        Console.Write(string.Format("{0} ", item));
    }
    Console.WriteLine();
}

3:输出

image

4:时间复杂度

根据时间复杂度的计算原则,冒泡排序为:O(n^2 )

  

C#选择排序

2011-08-18 16:40 by 陆敏技, 212 visits, 收藏, 编辑

1:原理

选择排序是从冒泡排序演化而来的,每一轮比较得出最小的那个值,然后依次和每轮比较的第一个值进行交换。
目的:按从小到大排序。
方法:假设存在数组:72, 54, 59, 30, 31, 78, 2, 77, 82, 72
第一轮依次比较相邻两个元素,将最小的一个元素的索引和值记录下来,然后和第一个元素进行交换。
如上面的数组中,首先比较的是72,54,记录比较小的索引是54的索引1。接着比较54和59,比较小的索引还是1。直到最后得到最小的索引是2的索引6,然后索引6和0互相交换。
第二轮比较的时候是最小的一个元素和索引1进行交换。第三轮、第四轮以此类推。
2:代码

class Program
{
    static List<int> list = new List<int>() { 72, 54, 59, 30, 31, 78, 2, 77, 82, 72 };
          
    static void Main(string[] args)
    {
        Choice();
        PrintList();
    }
 
    static void Choice()
    {
        int temp = 0;
        int minIndex = 0;
        for (int i = 0; i < list.Count; i++)
        {
            minIndex = i;
            for (int j = i; j < list.Count; j++)
            {
                //注意这里比较的是list[minIndex]
                if (list[j] < list[minIndex])
                {
                    minIndex = j;
                }
            }
            temp = list[minIndex];
            list[minIndex] = list[i];
            list[i] = temp;
            PrintList();
        }
 
    }
 
    private static void PrintList()
    {
        foreach (var item in list)
        {
            Console.Write(string.Format("{0} ", item));
        }
        Console.WriteLine();
    }
 
}

3:输出

image

4:时间复杂度

O(n^2)

原文地址:https://www.cnblogs.com/baiyu/p/2319169.html