模擬次數排序後尋找數值
/*
隨機產生n個(1-100)的0-100相異整數%%
比較排序前後找尋某一整數的次數%%
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a[101];
int i, j, t,N,flag,x,key,found=0,nn;
long tk;
unsigned seed;
seed = (unsigned)time(NULL);
srand(seed);
printf("正修科大 40404113 郭怡勝\n");
printf("請輸入模擬數目(<=100):");
scanf("%d",&N);
for(i=0; i<N; i++)
{
while(1)
{
flag=1;
x = rand() % 101;
for(j=0;j<=i-1;j++)
{
if( x == a[j])
{
flag=0;
break;
}
}
if(flag == 1)
{
a[i]=x;
break;
}
}
}
printf("\n原陣列:\n");
for (i=0; i<N; i++) printf("%3d",a[i]);
printf("\n\n請輸入要找的值:");
scanf("%d",&key);
for(i=0;i<N;i++)
{
if(key == a[i])
{
found=1;
break;
}
}
if(found == 1)
printf("找了 %3d 次,找到了",i+1);
else
printf("找了 %3d 次,找不到",i);
for (i=0; i<N-1; i++)
{
for (j=i+1; j<N; j++)
{
if (a[i]>a[j])
{
t = a[j];
a[j] = a[i];
a[i] = t;
}
}
/* printf("\n第 %d 回排序後最小值為 :", i+1);
printf("%3d ",a[i]);
printf(" 新陣列為: ", i+1);
for(j=i+1; j<N; j++)
printf("%d ",a[j]);
*/
}
printf("\n\n排序後\n");
for (i=0; i<N; i++) printf("%5d",a[i]);
printf("\n");
found=0;
for(i=0;i<N;i++)
{
if(key == a[i])
{
found=1;
nn=i+1;
break;
}
if(key < a[i])
{
found = 2;
nn=i+1;
break;
}
}
if(found == 1)
printf("找了 %3d 次,找到了",nn);
else
if(found == 2)
printf("找了 %3d 次,找不到",nn);
else
printf("找了 %3d 次,找不到",N);
return 0;
}