冒泡排序 和 选择排序
- 本文是有一个菜鸟级的大一学生写的,如果有什么改进的意见,可以提出来
冒泡排序
#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);