[C/C++ 演算法]- 循序搜尋法(使用衛兵)
[C/C++ 演算法]- 循序搜尋法(使用衛兵)
剛才找資料時發現一個C/C++的教學網站,趕快發揮(C/P)的長才將它備份來,有需要的同好,歡迎來(C/P)一下^^。
拷貝來源:
http://openhome.cc/Gossip/AlgorithmGossip/
http://openhome.cc/Gossip/AlgorithmGossip/LinearSearch.htm
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SWAP(x,y) {int t; t = x; x = y; y = t;}
int search(int[]);
int partition(int[], int, int);
void quickSort(int[], int, int);
int main(void) {
srand(time(NULL));
int number[MAX+1] = {0};
int i;
for(i = 1; i <= MAX; i++)
number[i] = rand() % 100;
quickSort(number, 1, MAX);
printf("數列:");
for(i = 1; i <= MAX; i++)
printf("%d ", number[i]);
printf("\n輸入搜尋值:");
scanf("%d", &number[0]);
int find = search(number);
if(find >= 0)
printf("\n找到數值於索引 %d ", find);
else
printf("\n找不到數值");
printf("\n");
return 0;
}
int search(int number[]) {
int i = MAX;
while(number[i] != number[0]) i--;
return i;
}
int partition(int number[], int left, int right) {
int s = number[right];
int i = left - 1;
int j;
for(j = left; j < right; j++) {
if(number[j] <= s) {
i++;
SWAP(number[i], number[j]);
}
}
SWAP(number[i+1], number[right]);
return i+1;
}
void quickSort(int number[], int left, int right) {
if(left < right) {
int q = partition(number, left, right);
quickSort(number, left, q-1);
quickSort(number, q+1, right);
}
}
|