2013-10-24 47 views
-2

我在寫一個遞歸二進制搜索程序。這是迄今爲止我所擁有的。這個程序的參數是它包含2個函數,主函數和第二個函數,它們將對它傳遞的值進行二進制排序。該項目工程,但它不遞歸搜索功能,我不認爲它使用二進制搜索...提高我的二進制搜索程序爲遞歸的嗎?

/* ex06_18.c */ 
#include <stdio.h> 
#define SIZE 10 

/* function prototype */ 
void someFunction(const int b[], int startIndex, int size); 

/* function main begins program execution */ 
int main(void) 
{ 
int a[ SIZE ] = { 8, 3, 1, 2, 6, 0, 9, 7, 4, 5 }; /* initialize a */ 
printf("Answer is:\n"); 
someFunction(a, 0, SIZE); 
printf("\n"); 
return 0; /* indicates successful termination */ 
} 
void someFunction(const int b[], int startIndex, int size) 
{ 
if (startIndex < size) { 
someFunction(b, startIndex + 1, size); 
printf("%d ", b[ startIndex ]); 
} /* end if */ 
} /* end function someFunction */ 
+2

「該項目工程」 - 除非你有一個完全不同的概念,「搜索」比其他人。 「它不會遞歸地搜索函數」 - 僅僅因爲它不搜索;它顯然是遞歸的。 「我不認爲它使用二分搜索」 - 你不覺得?你是否在課堂上跳過討論,沒有閱讀關於該主題的教科書?即使如此,通過谷歌提供的引用googol。 「二進制排序」 - 等待,現在你想排序?排序,搜索和打印出所有的值都是三種不同的東西。 –

回答

0

你正在做的只是打印陣列向後什麼,不是嗎?您可以在http://en.wikipedia.org/wiki/Binary_search_algorithm中閱讀二進制搜索算法。我沒有看到任何理由,你說它必須是一個遞歸函數。我更喜歡二元搜索的非遞歸函數,即使在維基百科鏈接中也有遞歸方法。

0

二進制搜索只如果你的數據集進行排序工作;否則,小於和大於比較是完全無用的,因爲它們沒有告訴你任何其他元素的位置。所以首先你需要確保你的數據集被排序 - 這是一個單獨的問題。

一旦你有一個排序的數據集,你要拿出遵循這個一般形式的函數(僞代碼,而不是實際的C++):

function search(needle, haystack, start, end) { 
    int middle_idx = haystack[(start+end)/2] 
    if(haystack[middle_idx] == needle) 
     return middle_idx; 
    else if(haystack[middle_idx] < needle) 
     return search(needle, haystack, start, middle_idx-1) 
    else if(haystack[middle_idx] > needle) 
     return search(needle, haystack, middle_idx+1, end) 

確保您處理任何邊緣案件彈出。特別是,想想如果針沒有在乾草堆中找到,會發生什麼;你能添加一些處理這種情況的東西嗎?