源码+注释
#include <malloc.h>
#include "stdio.h"
#include <stdlib.h>
#define MAXSIZE 2147483647
#define OK 1
#define ERROR 0
typedef struct {
int key;
int otherInfo;
} ElemType;
typedef struct {
ElemType *elem;
int length;
} SqSTable;
int InitTable(SqSTable *table);
int CreateTable(SqSTable *table, int length);
void knuthShuffle(SqSTable *table);
void swapInt(int *card_1, int *card_2);
int SearchSeq_01(SqSTable table, int key);
int SearchSeq_02(SqSTable table, int key);
int main() {
SqSTable table;
if (!(InitTable(&table))) {
printf("空间申请失败!!!");
}
CreateTable(&table, 122222);
printf("顺序查找一结果:%s \n", SearchSeq_01(table, 122223) == 0 ? "没有找到" : "找到了");
printf("顺序查找二结果:%s \n", SearchSeq_02(table, 0) == 0 ? "没有找到" : "找到了");
getchar();
}
int InitTable(SqSTable *table) {
table->elem = (ElemType *) malloc(sizeof(SqSTable) * MAXSIZE);
if (table->elem == NULL) {
return ERROR;
}
table->length = 0;
return OK;
}
int CreateTable(SqSTable *table, int length) {
if (table->length != 0) {
return ERROR;
}
for (int i = 1; i <= length; i++) {
table->elem[i].key = i;
table->length++;
}
knuthShuffle(table);
printf("\n");
return OK;
}
void knuthShuffle(SqSTable *table) {
for (int i = table->length; i >= 1; i--) {
swapInt(&(table->elem[i].key), &(table->elem[rand() % (i + 1) + 1].key));
}
}
void swapInt(int *card_1, int *card_2) {
int tCard;
tCard = *card_1;
*card_1 = *card_2;
*card_2 = tCard;
}
int SearchSeq_01(SqSTable table, int key) {
for (int i = table.length; i >= 1; i--) {
if (table.elem[i].key == key) {
return i;
}
}
return 0;
}
int SearchSeq_02(SqSTable table, int key) {
int i;
table.elem[0].key = key;
for (i = table.length; table.elem[i].key != key; i--);
return i;
}