排序法之快速排序法

1、引言

选择排序工作原理是每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法。选择排序是和冒泡排序差不多的一种排序。和冒泡排序交换相连数据不一样的是,选择排序只有在确定了最小的数据之后,才会发生交换。怎么交换呢?我们可以以下面一组数据作为测试

    2, 1, 5, 4, 9
    第一次排序:1, 2, 5, 4, 9
    第二次排序: 1, 2, 5, 4, 9
    第三次排序: 1, 2, 4, 5, 9
    第四次排序: 1, 2, 4, 5, 9
   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

2、算法思想

那么从上面的排序步骤可以看到,选择排序应该是这样的: 
(1)每次排序的时候都需要寻找第n小的数据,并且和array[n-1]发生交换 
(2)等到n个数据都排序好,那么选择排序结束。

3、代码

void select_sort(int array[], int length)
{
    int inner, outer, index, value, median;

    if(NULL == array || 0 == length)
        return;

    for(outer = 0; outer < length - 1; outer ++)
    {
        value = array[outer];
        index = outer;

        for(inner = outer +1; inner < length; inner ++){
            if(array[inner] < value){
                value = array[inner];
                index = inner;
            }
        }

        if(index == outer)
            continue;

        median = array[index];
        array[index] = array[outer];
        array[outer] = median;
    }
}

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

4、测试代码

void print(int array[], int length)
{
    int index;
    if(NULL == array || 0 == length)
        return;

    for(index = 0; index < length; index++)
        printf("%d", array[index]);
}

void test()
{
    int data[] = {2, 1, 5, 4, 9};
    int size = sizeof(data)/sizeof(int);
    select_sort(data, size);
    print(data, size);
}

   
   
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

5、分析

从选择排序的思想或者是上面的代码中,我们都不难看出,寻找最小的元素需要一个循环的过程,而排序又是需要一个循环的过程。因此显而易见,这个算法的时间复杂度也是O(n*n)的。这就意味值在n比较小的情况下,算法可以保证一定的速度,当n足够大时,算法的效率会降低。并且随着n的增大,算法的时间增长很快。因此使用时需要特别注意。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值