冒泡排序 和 选择排序

版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处! https://blog.csdn.net/apersonlikep/article/details/69216914

冒泡排序 和 选择排序

  • 本文是有一个菜鸟级的大一学生写的,如果有什么改进的意见,可以提出来

冒泡排序

#include <stdio.h>
#include <time.h>
#include <stdlib.h>



int main(void)
{
    int a[10];
    int count =0;
    int i,j;

    struct timespec tp;  
    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&tp);  
    srand(tp.tv_nsec); 
    for ( i = 0; i < 10; ++i)
    {

        a[i]= rand()%100;
    }
    for ( j = 0; j < 10; ++j)
    {

        /* code */
        count =0;

        for ( i = 0; i < 9; ++i)
        {
            /* code */

            if (a[i] > a[i+1])
            {
                /* code */
                int tmp = a[i];
                a[i]=a[i+1];
                a[i+1] = tmp;
            }
                count++;
        }

        if(count == 0)
            break;

    }
    for ( i = 0; i < 10; ++i)
    {
        /* code */
        printf("%02d ",a[i] );
    }
    return 0;
}

选择排序

#include <stdio.h>
#include <time.h>
#include <stdlib.h>



int main(void)
{
    int a[10];
    int count =0;
    int i,j,min;

    struct timespec tp;  
    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&tp);  
    srand(tp.tv_nsec); 
    for ( i = 0; i < 10; ++i)
    {

        a[i]= rand()%100;
    }
    for ( j = 0; j < 9; ++j)
    {
        min = a[j];
        /* code */
        count =0;

        for ( i = j+1; i < 10; ++i)
        {
            /* code */

            if (a[i] < min)
            {
                /* code */
                min = a[i];
                a[i] = a[j];
                a[j] =min;
                count++;
            }

        }

        if(count == 0)
            break;

    }
    for ( i = 0; i < 10; ++i)
    {
        /* code */
        printf("%02d ",a[i] );
    }
    return 0;
}

其中的之前的版本中 随机种子是通过srand(time(0))获取
但是由于时间的精确程度 srand(time(0))是1秒
所以在1秒内,所获取的序列是相同的,因此所种子也是相同的
所以要加精度 改为

    struct timespec tp;  
    clock_gettime(CLOCK_THREAD_CPUTIME_ID,&tp);  
    srand(tp.tv_nsec);

Linux下srand随机函数关于时间种子的精度提升

http://blog.csdn.net/u013172206/article/details/17350977

猜你喜欢

转载自blog.csdn.net/apersonlikep/article/details/69216914