#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h> //包含memsetd的函數
//對兩個數值型關鍵字的比較約定如下:
#define EQ(a,b) ((a) == (b))
#define LT(a,b) ((a) < (b))
#define LQ(a,b) ((a) <= (b))
#define OK 1;
#define KeyType int
//#define ElemType int
typedef struct KeyTable
{
KeyType key; //關鍵字字域
}ElemType;
struct SSTable
{
ElemType *elem; //資料元素存儲空間基址,建表時按實際長度配置設定,号單元留白
int length;
int cnt; //有效元素的個數
};
void Init_arr(SSTable *ST,ElemType *arr,int n);
void Creat_Seq(SSTable *ST,ElemType *arr,int n); //給數組指派
void Ascend(SSTable *ST); //重建靜态查找表,排序 升序
void Creat_Ord(SSTable *ST, ElemType *arr,int n);
int Destroy(SSTable *ST);
int Search_Seq(SSTable *ST,KeyType key);
int Search_Bin(SSTable *ST,KeyType key); //折半查找
void Traverse(SSTable *ST);
int main(void)
{
int seq,bin;
struct SSTable pSSTable;
ElemType r[] = {,,,,,};
Init_arr(&pSSTable,r,);
Creat_Seq(&pSSTable,r,6);
Traverse(&pSSTable);
Ascend(&pSSTable);
printf("排序後的元素為:\n");
Traverse(&pSSTable);
seq = Search_Seq(&pSSTable,3);
printf("順序查找元素的下标為:%d\n",seq);
bin = Search_Bin(&pSSTable,);
printf("折半查找元素的小标為:%d\n",bin);
return ;
}
void Init_arr(SSTable *ST,ElemType *arr,int n)
{
ST->elem = (ElemType *)calloc(n+,sizeof(ElemType));
if(NULL == ST->elem)
{
printf("動态記憶體配置設定失敗!\n");
exit(-);
}
else
{
memset(ST->elem,,n+);//初始化配置設定的記憶體區域,初始化為
ST->length = n+; //整個數組的長度
ST->cnt = ;
/* for(int i=0 ; i<n ; i++)
* {
* ST->elem[i+1] = arr[i];
* (ST->cnt)++;
* }
*/
}
}
void Creat_Seq(SSTable *ST,ElemType *arr,int n) //給數組指派
{
int i;
for(i= ,ST->cnt = ; i<n ; i++)
{
ST->elem[i+] = arr[i];
(ST->cnt)++;
}
}
void Ascend(SSTable *ST)
{
int i,j;
for(i= ; i<ST->cnt ; i++)
{
ST->elem[] = ST->elem[i]; //待比較值存[]單元
for(j=i+ ; j<=ST->cnt ; j++)
{
if(ST->elem[i].key > ST->elem[j].key)
{
ST->elem[] = ST->elem[j];
ST->elem[j] = ST->elem[i];
ST->elem[i] = ST->elem[];
}
}
}
}
int Destroy(SSTable *ST)
{
free(ST->elem);
ST->elem = NULL;
ST->length = ;
ST->cnt = ;
return OK;
}
int Search_Seq(SSTable *ST,KeyType key)
{
int i;
ST->elem[].key = key; //哨兵
for(i=ST->cnt ; key != (ST->elem[i].key) ; --i); //從前往後找
return i; //找不到i=
}
int Search_Bin(SSTable *ST,KeyType key) //折半查找
{
int low,high,mid;
low = ;
high = ST->cnt;
while(low <= high)
{
mid = (low + high)/;
if(key == ST->elem[mid].key)
return mid; //傳回查找元素的下标
else if(key < (ST->elem[mid].key))
high = mid -;
else
low = mid + ;
}
return ; //查找失敗傳回
}
void Traverse(SSTable *ST)
{
int i;
ElemType *p = ST->elem;
for(i = ;i <= ST->cnt ;i++)
printf(" %d",p[i].key);
printf("\n");
}