#include<stdlib.h>
#define MAX_SIZE 101
#define SWAP(x,y,t) ((t)=(x),(x)=(y),(y)=(t))
#define COMPARE(x,y) (((x) < (y))? -1:((x) == (y))?0:1)
void sort(int list[],int n);
int binsearch(int list[], int searchnum,int left, int right);
/**************************************************************
*Function Name:main
*Description :Test function sort and binsearch.
*Input :NULL.
*Output :NULL.
*Return :NULL
***************************************************************/
void main(void)
{
int i,n,searchnum,wjj;
int list[MAX_SIZE];
printf("Enter the number of numbers to generate: ");
scanf_s("%d",&n);
//检查输入n是否合法。
if(n<1 || n > MAX_SIZE)
{
fprintf(stderr,"Improper value of n\n");
exit(EXIT_FAILURE);
}
//为数组赋随机值,所有元素的值都在1000范围以内。
for(i=0;i<n;i++)
{
list[i] = rand()%1000;
printf("%d ",list[i]);
}
//排序操作
sort(list,n);
//打印排序后的数组
printf("\n Sorted array:\n");
for(i=0;i<n;i++)
printf("%d ",list[i]);
printf("\nEnter the num you want to search:");
scanf("%d",&searchnum);
wjj = binsearch(list, searchnum,0, n-1);
if(wjj!=-1)
{
printf("searchnum success!\n");
printf("The num you want to search is list[%d]",wjj);
}
else
printf("The num %d you want to search is not in the list.",searchnum);
printf("\n");
}
/**************************************************************
*Function Name:sort
*Description :From those integers that are currently unsorted,
* find the smallest and place it next in the sorted list.
* 在当前所有未排序的整数中,找出最小的一个,把它放在当前有序表的最后一个位置。
*Input :list address and the lengtn of list.
*Output :sorted list.
*Return :NULL
***************************************************************/
void sort(int list[],int n)
{
int i,j,min,temp;
for(i=0;i<n-1;i++)
{
min = i;
for(j=i+1;j<n;j++)
if(list[j]<list[min])
min = j;
SWAP(list[i],list[min],temp);
}
}
/**************************************************************
*Function Name:binsearchnum
*Description :find searchnum in list
*Input :list address , the num that you want to search
* and the scope (left and right)
*Output :NULL
*Return :find the searchnum return 0,else return -1.
***************************************************************/
int binsearch(int list[], int searchnum,int left, int right)
{
int middle;
while(left <= right)
{
middle = (left + right)/2 ;
switch(COMPARE(list[middle],searchnum))
{
case -1 :left = middle + 1;break;
case 0 :return middle;
case 1 :right = middle - 1;
default:printf("Impossible Thing!");
}
}
return -1;
}
选择排序法
最新推荐文章于 2023-02-12 20:42:34 发布