Skip to main content

Posts

Showing posts with the label Sample C Snippet code on binary search

Sample C Program To Implement Binary Search Without Using Recursive Function.

ALGORITHM: STEP 1: Start the program. STEP 2: Read the value of n. STEP 3: Set a for loop to read the elements of array. for(i = 0; i < n; i++) STEP 4: Set a for loop. for(i = 0; i < n; i++) STEP 5: Nest another for loop. for(j = i + 1; j < n; j++) STEP 6: Check the condition a[i] > a[j] STEP 7: If so swap the two values using temporary variable t as t = a[i] a[i] = a[j] a[j] = t STEP 8: Else go back to step 6. STEP 9: Set a for loop to print the value of array a. for(i = 0; i < n; i++) STEP 10: Read the search key as k. STEP 11: Assign low = 0 and high = n – 1. STEP 12: Call the function binsearch(a, k, low, high) STEP 13: Check if ans is not equal to 1, if so print the position b + i. else print that element is not found. STEP 14: Stop the program. FUNCTION BINARY SEARCH (int *a[ ], int x, int low, int high) STEP 1: Check if low > high if so return -1. STEP 2: Else assign mean value of low and high to mid. mid = ( high + ...

Sample C Program To Implement Binary Search Using Recursive Function.

ALGORITHM: STEP 1: Start the program. STEP 2: Read the value of n. STEP 3: Set a for loop to read the elements of array. for(i = 0; i < n; i++) STEP 4: Set a for loop. for(i = 0; i < n; i++) STEP 5: Nest another for loop. for(j = i + 1; j < n; j++) STEP 6: Check the condition a[i] > a[j]. STEP 7: If so swap the two values using temporary variable t as t = a[i] a[i] = a[j] a[j] = t STEP 8: Else go back to step 6. STEP 9: Set a for loop to print the value of array a. for(i = 0; i < n; i++) STEP 10: Read the search key as k. STEP 11: Assign low = 0 and high = n – 1. STEP 12: Call the function binsearch(a, k, low, high) STEP 13: Check if ans is not equal to 1, if so print the position b + i. Else print that element is not found. STEP 14: Stop the program. FUNCTION BINARY SEARCH (int *x[ ], int x, int low, int high) STEP 1: Set a while loop till low is greater than high. STEP 2: Assign mean value of low and high to mid. mid = (high...