Functions and Recursions – Arithmetic – Problem #16

IIT Kharagpur CS10001 / CS11001 Programming and Data Structures Lab Question Archive

Difficulty: easy

Problem Statement

User supplies a list of n distinct integers sorted in increasing order. First check if the list is sorted (in increasing order). He/She also supplies a key x, which is an integer. Assume that n lies in [1,20]. Store the list as a 1D array and write a program to search x in the array using (a) linear search and (b) binary search. Implement the linear search in linear_search() function and binary search in bin_search() function. Both the functions should take the list and the key x as argument and should return the index (for successful search, -1 for unsuccessful search). Ask the user to choose the required searching algorithm and invoke the respective function. In case of successful search, print in the main() the position of x in the array. Position of an element is indicated by its array index. In case of unsuccessful search, print -1. Implement the binary search using iterative procedure, NOT by recursion. In both the cases, print the messages in main function. Example 1: Enter the number of elements n: 5 Enter the elements in sorted order: 4, 8, 12, 18, 21 Enter the key element x, which you want to search: 12 Choose the algorithm: Type 1 for linear search and 2 for binary search 2 Executing the binary search algorithm Successful search Element 12 has been found at the index 2 Example 2: Enter the number of elements n: 5 Enter the elements in sorted order: 8, 4, 12, 18, 21 Not sorted. Enter again Enter the elements in sorted order: 4, 9, 12, 18, 21

Back to Lab Problems
Functions and Recursions/Arithmetic/Problem #16

Lab Problem Statement

Specifications & Problem DetailsIIT Kharagpur PDS Archive
Loading question...

Interactive C Compiler · Problem #16

WASM In-Browser

Runs directly on your machine · Zero remote server dependency

Compiler downloads on first Run (large, saved in your browser after that)
main.cCtrl + Enter to run
1
2
3
4
5
6
7
Input (stdin)given to scanf / cin
Output

Output appears here. Press Run to compile and execute.