SlideShare a Scribd company logo
Question 1,2,4 :-
-----------------------------------
Please check comments in Programme
#include
/**
* Method for Linear Search
* Loop through given array and search for given key
* IF found return index and stop
* else -1 will be returned at the end
*
*/
int search(int array[],int key,int size){
int index = -1;
for (int c = 0; c < size; c++)
{
if (array[c] == key) /* if required element found */
{
printf("%d is present at location %d. ", key, c+1);
index = c;
break;
}
}
if(index == -1)
printf("%d is not found. ", key);
return index;
}
/**
* Function for Binary search
* Binary search is used only for sorted arrays
* Check key with element at middle position
* if key == then return middle positon
* if key > middle position , apply same for sub array range from [middle...last]
* if key < middle position , apply same for sub array range from [0..middle]
*
*/
int binary_search(int array[],int key,int start,int end){
int index = -1;
int first = start;
int last = end;
int middle = (first+last)/2;
while (first <= last) {
//Print array between first nad last for each step
printf("Start binary search step. ");
for(int i = first ; i < last ; i++){
printf("Binary search step element.%d ",array[i]);
}
printf("Stop binary search step. ");
if (array[middle] < key)
first = middle + 1;
else if (array[middle] == key) {
index = middle;
printf("%d found at location %d. ", key, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
return index;
}
/**
* Recursive linear search
* Instead of for loop call same method with next index
* first pass 0, check if key found at index 0, if not found call same method with index 1 .....
*/
int linear_search_recursive(int array[],int key,int size,int index){
if(array[index] == key){
printf("%d found at location %d. ",key, index);
return index;
}
else if (index >= size-1){
return -1;
}
else{
return linear_search_recursive(array,key,size,++index);
}
}
/**
* Recursive Binary Search
* Recursively call Binary Search , check key found at element middle
* if key == then return middle positon
* if key > middle position , call recursive method for sub array range from [middle...last]
* if key < middle position , call recursive method for sub array range from [0..middle]
*/
int binary_search_recursive(int array[],int key,int start,int end){
//Key not found
if(start> end){
return -1;
}
int index = -1;
int first = start;
int last = end;
int middle = (first+last)/2;
//Print array between first nad last for each step
printf("Start binary search step. ");
for(int i = first ; i < last ; i++){
printf("Binary search step element.%d ",array[i]);
}
printf("Stop binary search step. ");
if (array[middle] < key){
first = middle + 1;
return binary_search_recursive(array,key,first,last) ;
}else if (array[middle] == key) {
printf("%d found at location %d. ", key, middle+1);
return middle;
}
else{
last = middle - 1;
return binary_search_recursive(array,key,first,last) ;
}
return -1;
}
/**
*Function to sort the array
* for Binary search we have to sort array first
*/
void sort(int number[], int size){
for (int i = 0; i < size; ++i)
{
for (int j = i + 1; j < size; ++j)
{
if (number[i] > number[j])
{
int a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
}
int main(int argc, char *argv[])
{
int range = 100;
int data[100];
for(int i = 0 ; i < 100 ; i++){
int item = rand() % range + 1;
data[i] = item;
printf("array item %d : %d  ",i,item);
}
sort(data,range);
//search(data,120,100);
//binary_search(data,41,0,99);
//linear_search_recursive(data,41,100,0);
binary_search_recursive(data,91,0,99);
return 0;
}
Question 3 :-
-------------------------------
To test with 1000 elements
change the variable "range" , assign 1000 to it
worst Time Complexity of Linear search is alwasy O(n), becuase we have to lop throug all
elements in array
For Binary search it is O(n/2) , but array shuld be sorted first
Time complexity for Binaru Searc = Time Complexity ofSorting + Time complexity of Search
Question 5 (Using Linked List):-
--------------------------------
#include
#include
#include
#include
struct node
{
int data;
int key;
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
//display the list
void printList()
{
struct node *ptr = head;
printf(" [ ");
//start from the beginning
while(ptr != NULL)
{
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
printf(" ]");
}
//insert link at the first location
void insertFirst(int key, int data)
{
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(current == NULL){
head = link;
current = head;
}
else{
//append after head
current->next = link;
current = link;
}
}
//is list empty
bool isEmpty()
{
return head == NULL;
}
int length()
{
int length = 0;
struct node *current;
for(current = head; current != NULL; current = current->next)
{
length++;
}
return length;
}
//find a link with given key
struct node* find(int key){
int index = -1;
//start from the first link
struct node* cur = head;
//if list is empty
if(head == NULL)
{
return NULL;
}
//navigate through list
while( cur != NULL ){
if(cur->data == key){
index = cur->key;
break;
}
//if it is last node
if(cur->next == NULL){
index = -1;
break;
}else {
//go to next link
cur = cur->next;
}
}
if(index == -1){
printf("element not found");
}
else{
printf("element found at %d", index);
}
//if data found, return the current Link
return current;
}
int main(){
int range = 100;
for(int i = 0 ; i < 100 ; i++){
int item = rand() % range + 1;
insertFirst(i,item);
printf("array item %d : %d  ",i,item);
}
struct node* search = find(84);
return 0;
}
Solution
Question 1,2,4 :-
-----------------------------------
Please check comments in Programme
#include
/**
* Method for Linear Search
* Loop through given array and search for given key
* IF found return index and stop
* else -1 will be returned at the end
*
*/
int search(int array[],int key,int size){
int index = -1;
for (int c = 0; c < size; c++)
{
if (array[c] == key) /* if required element found */
{
printf("%d is present at location %d. ", key, c+1);
index = c;
break;
}
}
if(index == -1)
printf("%d is not found. ", key);
return index;
}
/**
* Function for Binary search
* Binary search is used only for sorted arrays
* Check key with element at middle position
* if key == then return middle positon
* if key > middle position , apply same for sub array range from [middle...last]
* if key < middle position , apply same for sub array range from [0..middle]
*
*/
int binary_search(int array[],int key,int start,int end){
int index = -1;
int first = start;
int last = end;
int middle = (first+last)/2;
while (first <= last) {
//Print array between first nad last for each step
printf("Start binary search step. ");
for(int i = first ; i < last ; i++){
printf("Binary search step element.%d ",array[i]);
}
printf("Stop binary search step. ");
if (array[middle] < key)
first = middle + 1;
else if (array[middle] == key) {
index = middle;
printf("%d found at location %d. ", key, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
return index;
}
/**
* Recursive linear search
* Instead of for loop call same method with next index
* first pass 0, check if key found at index 0, if not found call same method with index 1 .....
*/
int linear_search_recursive(int array[],int key,int size,int index){
if(array[index] == key){
printf("%d found at location %d. ",key, index);
return index;
}
else if (index >= size-1){
return -1;
}
else{
return linear_search_recursive(array,key,size,++index);
}
}
/**
* Recursive Binary Search
* Recursively call Binary Search , check key found at element middle
* if key == then return middle positon
* if key > middle position , call recursive method for sub array range from [middle...last]
* if key < middle position , call recursive method for sub array range from [0..middle]
*/
int binary_search_recursive(int array[],int key,int start,int end){
//Key not found
if(start> end){
return -1;
}
int index = -1;
int first = start;
int last = end;
int middle = (first+last)/2;
//Print array between first nad last for each step
printf("Start binary search step. ");
for(int i = first ; i < last ; i++){
printf("Binary search step element.%d ",array[i]);
}
printf("Stop binary search step. ");
if (array[middle] < key){
first = middle + 1;
return binary_search_recursive(array,key,first,last) ;
}else if (array[middle] == key) {
printf("%d found at location %d. ", key, middle+1);
return middle;
}
else{
last = middle - 1;
return binary_search_recursive(array,key,first,last) ;
}
return -1;
}
/**
*Function to sort the array
* for Binary search we have to sort array first
*/
void sort(int number[], int size){
for (int i = 0; i < size; ++i)
{
for (int j = i + 1; j < size; ++j)
{
if (number[i] > number[j])
{
int a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
}
int main(int argc, char *argv[])
{
int range = 100;
int data[100];
for(int i = 0 ; i < 100 ; i++){
int item = rand() % range + 1;
data[i] = item;
printf("array item %d : %d  ",i,item);
}
sort(data,range);
//search(data,120,100);
//binary_search(data,41,0,99);
//linear_search_recursive(data,41,100,0);
binary_search_recursive(data,91,0,99);
return 0;
}
Question 3 :-
-------------------------------
To test with 1000 elements
change the variable "range" , assign 1000 to it
worst Time Complexity of Linear search is alwasy O(n), becuase we have to lop throug all
elements in array
For Binary search it is O(n/2) , but array shuld be sorted first
Time complexity for Binaru Searc = Time Complexity ofSorting + Time complexity of Search
Question 5 (Using Linked List):-
--------------------------------
#include
#include
#include
#include
struct node
{
int data;
int key;
struct node *next;
};
struct node *head = NULL;
struct node *current = NULL;
//display the list
void printList()
{
struct node *ptr = head;
printf(" [ ");
//start from the beginning
while(ptr != NULL)
{
printf("(%d,%d) ",ptr->key,ptr->data);
ptr = ptr->next;
}
printf(" ]");
}
//insert link at the first location
void insertFirst(int key, int data)
{
//create a link
struct node *link = (struct node*) malloc(sizeof(struct node));
link->key = key;
link->data = data;
if(current == NULL){
head = link;
current = head;
}
else{
//append after head
current->next = link;
current = link;
}
}
//is list empty
bool isEmpty()
{
return head == NULL;
}
int length()
{
int length = 0;
struct node *current;
for(current = head; current != NULL; current = current->next)
{
length++;
}
return length;
}
//find a link with given key
struct node* find(int key){
int index = -1;
//start from the first link
struct node* cur = head;
//if list is empty
if(head == NULL)
{
return NULL;
}
//navigate through list
while( cur != NULL ){
if(cur->data == key){
index = cur->key;
break;
}
//if it is last node
if(cur->next == NULL){
index = -1;
break;
}else {
//go to next link
cur = cur->next;
}
}
if(index == -1){
printf("element not found");
}
else{
printf("element found at %d", index);
}
//if data found, return the current Link
return current;
}
int main(){
int range = 100;
for(int i = 0 ; i < 100 ; i++){
int item = rand() % range + 1;
insertFirst(i,item);
printf("array item %d : %d  ",i,item);
}
struct node* search = find(84);
return 0;
}

More Related Content

Similar to Question 1,2,4 ------------------------------------Please check.pdf

DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
KamalSaini561034
 
Pointers and arrays
Pointers and arraysPointers and arrays
Pointers and arrays
Bhuvana Gowtham
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
debishakespeare
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)
Ankit Gupta
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
Rahul04August
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdf
JkPoppy
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
davidwarner122
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
archgeetsenterprises
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
michardsonkhaicarr37
 
Linked lists
Linked listsLinked lists
Linked lists
George Scott IV
 
Refer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdfRefer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdf
arishmarketing21
 
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
odiliagilby
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
arihantelehyb
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
Nauman Rehman
 
a) Complete both insert and delete methods. If it works correctly 10.pdf
a) Complete both insert and delete methods. If it works correctly 10.pdfa) Complete both insert and delete methods. If it works correctly 10.pdf
a) Complete both insert and delete methods. If it works correctly 10.pdf
MAYANKBANSAL1981
 
Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdf
shanki7
 
Program of sorting using shell sort #include stdio.h #de.pdf
 Program of sorting using shell sort  #include stdio.h #de.pdf Program of sorting using shell sort  #include stdio.h #de.pdf
Program of sorting using shell sort #include stdio.h #de.pdf
anujmkt
 
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfMerge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
mdameer02
 
Problem 1 Show the comparison of runtime of linear search and binar.pdf
Problem 1 Show the comparison of runtime of linear search and binar.pdfProblem 1 Show the comparison of runtime of linear search and binar.pdf
Problem 1 Show the comparison of runtime of linear search and binar.pdf
ebrahimbadushata00
 

Similar to Question 1,2,4 ------------------------------------Please check.pdf (20)

DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
 
Pointers and arrays
Pointers and arraysPointers and arrays
Pointers and arrays
 
Required to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docxRequired to augment the authors Binary Search Tree (BST) code to .docx
Required to augment the authors Binary Search Tree (BST) code to .docx
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
 
program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)program on string in java Lab file 2 (3-year)
program on string in java Lab file 2 (3-year)
 
C++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdfC++ Searching & Sorting5. Sort the following list using the select.pdf
C++ Searching & Sorting5. Sort the following list using the select.pdf
 
Swift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdfSwift 5.1 Language Guide Notes.pdf
Swift 5.1 Language Guide Notes.pdf
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
 
in this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdfin this assignment you are asked to write a simple driver program an.pdf
in this assignment you are asked to write a simple driver program an.pdf
 
Linked lists
Linked listsLinked lists
Linked lists
 
Refer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdfRefer to my progress on this assignment belowIn this problem you w.pdf
Refer to my progress on this assignment belowIn this problem you w.pdf
 
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
__MACOSX._assign3assign3.DS_Store__MACOSXassign3._.D.docx
 
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdf
 
Learn c++ (functions) with nauman ur rehman
Learn  c++ (functions) with nauman ur rehmanLearn  c++ (functions) with nauman ur rehman
Learn c++ (functions) with nauman ur rehman
 
a) Complete both insert and delete methods. If it works correctly 10.pdf
a) Complete both insert and delete methods. If it works correctly 10.pdfa) Complete both insert and delete methods. If it works correctly 10.pdf
a) Complete both insert and delete methods. If it works correctly 10.pdf
 
Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdf
 
Program of sorting using shell sort #include stdio.h #de.pdf
 Program of sorting using shell sort  #include stdio.h #de.pdf Program of sorting using shell sort  #include stdio.h #de.pdf
Program of sorting using shell sort #include stdio.h #de.pdf
 
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdfMerge Sort implementation in C++ The implementation for Mergesort gi.pdf
Merge Sort implementation in C++ The implementation for Mergesort gi.pdf
 
Problem 1 Show the comparison of runtime of linear search and binar.pdf
Problem 1 Show the comparison of runtime of linear search and binar.pdfProblem 1 Show the comparison of runtime of linear search and binar.pdf
Problem 1 Show the comparison of runtime of linear search and binar.pdf
 

More from anandhomeneeds

Driver.java import java.util.Scanner; import java.text.Decimal.pdf
Driver.java import java.util.Scanner; import java.text.Decimal.pdfDriver.java import java.util.Scanner; import java.text.Decimal.pdf
Driver.java import java.util.Scanner; import java.text.Decimal.pdf
anandhomeneeds
 
The answer is C. securin.APC degrade securin to release separase .pdf
The answer is C. securin.APC degrade securin to release separase .pdfThe answer is C. securin.APC degrade securin to release separase .pdf
The answer is C. securin.APC degrade securin to release separase .pdf
anandhomeneeds
 
HiCan you please summarise the question. More information confuse .pdf
HiCan you please summarise the question. More information confuse .pdfHiCan you please summarise the question. More information confuse .pdf
HiCan you please summarise the question. More information confuse .pdf
anandhomeneeds
 
What property of proteins us used to separate them in HICHydrophob.pdf
What property of proteins us used to separate them in HICHydrophob.pdfWhat property of proteins us used to separate them in HICHydrophob.pdf
What property of proteins us used to separate them in HICHydrophob.pdf
anandhomeneeds
 
upload complete priblem somthing is missingSolutionupload comp.pdf
upload complete priblem somthing is missingSolutionupload comp.pdfupload complete priblem somthing is missingSolutionupload comp.pdf
upload complete priblem somthing is missingSolutionupload comp.pdf
anandhomeneeds
 
the phenomena responsible for this type of inheritancce is Epistasis.pdf
the phenomena responsible for this type of inheritancce is Epistasis.pdfthe phenomena responsible for this type of inheritancce is Epistasis.pdf
the phenomena responsible for this type of inheritancce is Epistasis.pdf
anandhomeneeds
 
The substrate in urease test is urea.The end products in urease te.pdf
The substrate in urease test is urea.The end products in urease te.pdfThe substrate in urease test is urea.The end products in urease te.pdf
The substrate in urease test is urea.The end products in urease te.pdf
anandhomeneeds
 
later we create a specialstack class ,which inherits from stack cl.pdf
later we create a specialstack class ,which inherits from stack cl.pdflater we create a specialstack class ,which inherits from stack cl.pdf
later we create a specialstack class ,which inherits from stack cl.pdf
anandhomeneeds
 
I think that 34SolutionI think that 34.pdf
I think that 34SolutionI think that 34.pdfI think that 34SolutionI think that 34.pdf
I think that 34SolutionI think that 34.pdf
anandhomeneeds
 
D(ANSWER)Polycrystalline or multicrystalline materials, or polycry.pdf
D(ANSWER)Polycrystalline or multicrystalline materials, or polycry.pdfD(ANSWER)Polycrystalline or multicrystalline materials, or polycry.pdf
D(ANSWER)Polycrystalline or multicrystalline materials, or polycry.pdf
anandhomeneeds
 
1.It is the process of directing the television assistances are tran.pdf
1.It is the process of directing the television assistances are tran.pdf1.It is the process of directing the television assistances are tran.pdf
1.It is the process of directing the television assistances are tran.pdf
anandhomeneeds
 
Answer The major objective of implementing a health information man.pdf
Answer The major objective of implementing a health information man.pdfAnswer The major objective of implementing a health information man.pdf
Answer The major objective of implementing a health information man.pdf
anandhomeneeds
 
The key assumptions made by the Hadoop Distributed File System(HDFS).pdf
The key assumptions made by the Hadoop Distributed File System(HDFS).pdfThe key assumptions made by the Hadoop Distributed File System(HDFS).pdf
The key assumptions made by the Hadoop Distributed File System(HDFS).pdf
anandhomeneeds
 
Properties areMeanModeMedianQuartilesPercentilesRan.pdf
Properties areMeanModeMedianQuartilesPercentilesRan.pdfProperties areMeanModeMedianQuartilesPercentilesRan.pdf
Properties areMeanModeMedianQuartilesPercentilesRan.pdf
anandhomeneeds
 
MgCO3 Increasing acidity will cause the following reaction Mg.pdf
 MgCO3 Increasing acidity will cause the following reaction Mg.pdf MgCO3 Increasing acidity will cause the following reaction Mg.pdf
MgCO3 Increasing acidity will cause the following reaction Mg.pdf
anandhomeneeds
 
Environmental conditions play a key role in defining the function an.pdf
Environmental conditions play a key role in defining the function an.pdfEnvironmental conditions play a key role in defining the function an.pdf
Environmental conditions play a key role in defining the function an.pdf
anandhomeneeds
 
1. Autralopith is a known genus of hominids which is extinct today..pdf
1. Autralopith is a known genus of hominids which is extinct today..pdf1. Autralopith is a known genus of hominids which is extinct today..pdf
1. Autralopith is a known genus of hominids which is extinct today..pdf
anandhomeneeds
 
Mobile IP1) Mobile IP(MIP) is an Internet Engineering Task Force(.pdf
Mobile IP1) Mobile IP(MIP) is an Internet Engineering Task Force(.pdfMobile IP1) Mobile IP(MIP) is an Internet Engineering Task Force(.pdf
Mobile IP1) Mobile IP(MIP) is an Internet Engineering Task Force(.pdf
anandhomeneeds
 
Answer1. Cells can generate many different tissue types endoderm,.pdf
Answer1. Cells can generate many different tissue types endoderm,.pdfAnswer1. Cells can generate many different tissue types endoderm,.pdf
Answer1. Cells can generate many different tissue types endoderm,.pdf
anandhomeneeds
 
3 a) The trace of an nSolution3 a) The trace of an n.pdf
3 a) The trace of an nSolution3 a) The trace of an n.pdf3 a) The trace of an nSolution3 a) The trace of an n.pdf
3 a) The trace of an nSolution3 a) The trace of an n.pdf
anandhomeneeds
 

More from anandhomeneeds (20)

Driver.java import java.util.Scanner; import java.text.Decimal.pdf
Driver.java import java.util.Scanner; import java.text.Decimal.pdfDriver.java import java.util.Scanner; import java.text.Decimal.pdf
Driver.java import java.util.Scanner; import java.text.Decimal.pdf
 
The answer is C. securin.APC degrade securin to release separase .pdf
The answer is C. securin.APC degrade securin to release separase .pdfThe answer is C. securin.APC degrade securin to release separase .pdf
The answer is C. securin.APC degrade securin to release separase .pdf
 
HiCan you please summarise the question. More information confuse .pdf
HiCan you please summarise the question. More information confuse .pdfHiCan you please summarise the question. More information confuse .pdf
HiCan you please summarise the question. More information confuse .pdf
 
What property of proteins us used to separate them in HICHydrophob.pdf
What property of proteins us used to separate them in HICHydrophob.pdfWhat property of proteins us used to separate them in HICHydrophob.pdf
What property of proteins us used to separate them in HICHydrophob.pdf
 
upload complete priblem somthing is missingSolutionupload comp.pdf
upload complete priblem somthing is missingSolutionupload comp.pdfupload complete priblem somthing is missingSolutionupload comp.pdf
upload complete priblem somthing is missingSolutionupload comp.pdf
 
the phenomena responsible for this type of inheritancce is Epistasis.pdf
the phenomena responsible for this type of inheritancce is Epistasis.pdfthe phenomena responsible for this type of inheritancce is Epistasis.pdf
the phenomena responsible for this type of inheritancce is Epistasis.pdf
 
The substrate in urease test is urea.The end products in urease te.pdf
The substrate in urease test is urea.The end products in urease te.pdfThe substrate in urease test is urea.The end products in urease te.pdf
The substrate in urease test is urea.The end products in urease te.pdf
 
later we create a specialstack class ,which inherits from stack cl.pdf
later we create a specialstack class ,which inherits from stack cl.pdflater we create a specialstack class ,which inherits from stack cl.pdf
later we create a specialstack class ,which inherits from stack cl.pdf
 
I think that 34SolutionI think that 34.pdf
I think that 34SolutionI think that 34.pdfI think that 34SolutionI think that 34.pdf
I think that 34SolutionI think that 34.pdf
 
D(ANSWER)Polycrystalline or multicrystalline materials, or polycry.pdf
D(ANSWER)Polycrystalline or multicrystalline materials, or polycry.pdfD(ANSWER)Polycrystalline or multicrystalline materials, or polycry.pdf
D(ANSWER)Polycrystalline or multicrystalline materials, or polycry.pdf
 
1.It is the process of directing the television assistances are tran.pdf
1.It is the process of directing the television assistances are tran.pdf1.It is the process of directing the television assistances are tran.pdf
1.It is the process of directing the television assistances are tran.pdf
 
Answer The major objective of implementing a health information man.pdf
Answer The major objective of implementing a health information man.pdfAnswer The major objective of implementing a health information man.pdf
Answer The major objective of implementing a health information man.pdf
 
The key assumptions made by the Hadoop Distributed File System(HDFS).pdf
The key assumptions made by the Hadoop Distributed File System(HDFS).pdfThe key assumptions made by the Hadoop Distributed File System(HDFS).pdf
The key assumptions made by the Hadoop Distributed File System(HDFS).pdf
 
Properties areMeanModeMedianQuartilesPercentilesRan.pdf
Properties areMeanModeMedianQuartilesPercentilesRan.pdfProperties areMeanModeMedianQuartilesPercentilesRan.pdf
Properties areMeanModeMedianQuartilesPercentilesRan.pdf
 
MgCO3 Increasing acidity will cause the following reaction Mg.pdf
 MgCO3 Increasing acidity will cause the following reaction Mg.pdf MgCO3 Increasing acidity will cause the following reaction Mg.pdf
MgCO3 Increasing acidity will cause the following reaction Mg.pdf
 
Environmental conditions play a key role in defining the function an.pdf
Environmental conditions play a key role in defining the function an.pdfEnvironmental conditions play a key role in defining the function an.pdf
Environmental conditions play a key role in defining the function an.pdf
 
1. Autralopith is a known genus of hominids which is extinct today..pdf
1. Autralopith is a known genus of hominids which is extinct today..pdf1. Autralopith is a known genus of hominids which is extinct today..pdf
1. Autralopith is a known genus of hominids which is extinct today..pdf
 
Mobile IP1) Mobile IP(MIP) is an Internet Engineering Task Force(.pdf
Mobile IP1) Mobile IP(MIP) is an Internet Engineering Task Force(.pdfMobile IP1) Mobile IP(MIP) is an Internet Engineering Task Force(.pdf
Mobile IP1) Mobile IP(MIP) is an Internet Engineering Task Force(.pdf
 
Answer1. Cells can generate many different tissue types endoderm,.pdf
Answer1. Cells can generate many different tissue types endoderm,.pdfAnswer1. Cells can generate many different tissue types endoderm,.pdf
Answer1. Cells can generate many different tissue types endoderm,.pdf
 
3 a) The trace of an nSolution3 a) The trace of an n.pdf
3 a) The trace of an nSolution3 a) The trace of an n.pdf3 a) The trace of an nSolution3 a) The trace of an n.pdf
3 a) The trace of an nSolution3 a) The trace of an n.pdf
 

Recently uploaded

How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
Celine George
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
Celine George
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
Jean Carlos Nunes Paixão
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
TechSoup
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
Nicholas Montgomery
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
simonomuemu
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
paigestewart1632
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
chanes7
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
Dr. Shivangi Singh Parihar
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
adhitya5119
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
Katrina Pritchard
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
RAHUL
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
taiba qazi
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
Celine George
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 

Recently uploaded (20)

How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17How to Make a Field Mandatory in Odoo 17
How to Make a Field Mandatory in Odoo 17
 
How to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP ModuleHow to Add Chatter in the odoo 17 ERP Module
How to Add Chatter in the odoo 17 ERP Module
 
A Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdfA Independência da América Espanhola LAPBOOK.pdf
A Independência da América Espanhola LAPBOOK.pdf
 
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat  Leveraging AI for Diversity, Equity, and InclusionExecutive Directors Chat  Leveraging AI for Diversity, Equity, and Inclusion
Executive Directors Chat Leveraging AI for Diversity, Equity, and Inclusion
 
Film vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movieFilm vocab for eal 3 students: Australia the movie
Film vocab for eal 3 students: Australia the movie
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
Smart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICTSmart-Money for SMC traders good time and ICT
Smart-Money for SMC traders good time and ICT
 
Cognitive Development Adolescence Psychology
Cognitive Development Adolescence PsychologyCognitive Development Adolescence Psychology
Cognitive Development Adolescence Psychology
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Digital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments UnitDigital Artifact 1 - 10VCD Environments Unit
Digital Artifact 1 - 10VCD Environments Unit
 
PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.PCOS corelations and management through Ayurveda.
PCOS corelations and management through Ayurveda.
 
Main Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docxMain Java[All of the Base Concepts}.docx
Main Java[All of the Base Concepts}.docx
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
BBR 2024 Summer Sessions Interview Training
BBR  2024 Summer Sessions Interview TrainingBBR  2024 Summer Sessions Interview Training
BBR 2024 Summer Sessions Interview Training
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UPLAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
LAND USE LAND COVER AND NDVI OF MIRZAPUR DISTRICT, UP
 
DRUGS AND ITS classification slide share
DRUGS AND ITS classification slide shareDRUGS AND ITS classification slide share
DRUGS AND ITS classification slide share
 
How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17How to Fix the Import Error in the Odoo 17
How to Fix the Import Error in the Odoo 17
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 

Question 1,2,4 ------------------------------------Please check.pdf

  • 1. Question 1,2,4 :- ----------------------------------- Please check comments in Programme #include /** * Method for Linear Search * Loop through given array and search for given key * IF found return index and stop * else -1 will be returned at the end * */ int search(int array[],int key,int size){ int index = -1; for (int c = 0; c < size; c++) { if (array[c] == key) /* if required element found */ { printf("%d is present at location %d. ", key, c+1); index = c; break; } } if(index == -1) printf("%d is not found. ", key); return index; } /** * Function for Binary search * Binary search is used only for sorted arrays * Check key with element at middle position * if key == then return middle positon * if key > middle position , apply same for sub array range from [middle...last] * if key < middle position , apply same for sub array range from [0..middle] * */
  • 2. int binary_search(int array[],int key,int start,int end){ int index = -1; int first = start; int last = end; int middle = (first+last)/2; while (first <= last) { //Print array between first nad last for each step printf("Start binary search step. "); for(int i = first ; i < last ; i++){ printf("Binary search step element.%d ",array[i]); } printf("Stop binary search step. "); if (array[middle] < key) first = middle + 1; else if (array[middle] == key) { index = middle; printf("%d found at location %d. ", key, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } return index; } /** * Recursive linear search * Instead of for loop call same method with next index * first pass 0, check if key found at index 0, if not found call same method with index 1 ..... */ int linear_search_recursive(int array[],int key,int size,int index){ if(array[index] == key){ printf("%d found at location %d. ",key, index); return index; } else if (index >= size-1){
  • 3. return -1; } else{ return linear_search_recursive(array,key,size,++index); } } /** * Recursive Binary Search * Recursively call Binary Search , check key found at element middle * if key == then return middle positon * if key > middle position , call recursive method for sub array range from [middle...last] * if key < middle position , call recursive method for sub array range from [0..middle] */ int binary_search_recursive(int array[],int key,int start,int end){ //Key not found if(start> end){ return -1; } int index = -1; int first = start; int last = end; int middle = (first+last)/2; //Print array between first nad last for each step printf("Start binary search step. "); for(int i = first ; i < last ; i++){ printf("Binary search step element.%d ",array[i]); } printf("Stop binary search step. "); if (array[middle] < key){ first = middle + 1; return binary_search_recursive(array,key,first,last) ; }else if (array[middle] == key) { printf("%d found at location %d. ", key, middle+1); return middle; } else{
  • 4. last = middle - 1; return binary_search_recursive(array,key,first,last) ; } return -1; } /** *Function to sort the array * for Binary search we have to sort array first */ void sort(int number[], int size){ for (int i = 0; i < size; ++i) { for (int j = i + 1; j < size; ++j) { if (number[i] > number[j]) { int a = number[i]; number[i] = number[j]; number[j] = a; } } } } int main(int argc, char *argv[]) { int range = 100; int data[100]; for(int i = 0 ; i < 100 ; i++){ int item = rand() % range + 1; data[i] = item; printf("array item %d : %d ",i,item); } sort(data,range); //search(data,120,100); //binary_search(data,41,0,99); //linear_search_recursive(data,41,100,0);
  • 5. binary_search_recursive(data,91,0,99); return 0; } Question 3 :- ------------------------------- To test with 1000 elements change the variable "range" , assign 1000 to it worst Time Complexity of Linear search is alwasy O(n), becuase we have to lop throug all elements in array For Binary search it is O(n/2) , but array shuld be sorted first Time complexity for Binaru Searc = Time Complexity ofSorting + Time complexity of Search Question 5 (Using Linked List):- -------------------------------- #include #include #include #include struct node { int data; int key; struct node *next; }; struct node *head = NULL; struct node *current = NULL; //display the list void printList() { struct node *ptr = head; printf(" [ "); //start from the beginning while(ptr != NULL) { printf("(%d,%d) ",ptr->key,ptr->data); ptr = ptr->next;
  • 6. } printf(" ]"); } //insert link at the first location void insertFirst(int key, int data) { //create a link struct node *link = (struct node*) malloc(sizeof(struct node)); link->key = key; link->data = data; if(current == NULL){ head = link; current = head; } else{ //append after head current->next = link; current = link; } } //is list empty bool isEmpty() { return head == NULL; } int length() { int length = 0; struct node *current; for(current = head; current != NULL; current = current->next) { length++; } return length; } //find a link with given key
  • 7. struct node* find(int key){ int index = -1; //start from the first link struct node* cur = head; //if list is empty if(head == NULL) { return NULL; } //navigate through list while( cur != NULL ){ if(cur->data == key){ index = cur->key; break; } //if it is last node if(cur->next == NULL){ index = -1; break; }else { //go to next link cur = cur->next; } } if(index == -1){ printf("element not found"); } else{ printf("element found at %d", index); } //if data found, return the current Link return current; } int main(){ int range = 100; for(int i = 0 ; i < 100 ; i++){
  • 8. int item = rand() % range + 1; insertFirst(i,item); printf("array item %d : %d ",i,item); } struct node* search = find(84); return 0; } Solution Question 1,2,4 :- ----------------------------------- Please check comments in Programme #include /** * Method for Linear Search * Loop through given array and search for given key * IF found return index and stop * else -1 will be returned at the end * */ int search(int array[],int key,int size){ int index = -1; for (int c = 0; c < size; c++) { if (array[c] == key) /* if required element found */ { printf("%d is present at location %d. ", key, c+1); index = c; break; } } if(index == -1) printf("%d is not found. ", key); return index; }
  • 9. /** * Function for Binary search * Binary search is used only for sorted arrays * Check key with element at middle position * if key == then return middle positon * if key > middle position , apply same for sub array range from [middle...last] * if key < middle position , apply same for sub array range from [0..middle] * */ int binary_search(int array[],int key,int start,int end){ int index = -1; int first = start; int last = end; int middle = (first+last)/2; while (first <= last) { //Print array between first nad last for each step printf("Start binary search step. "); for(int i = first ; i < last ; i++){ printf("Binary search step element.%d ",array[i]); } printf("Stop binary search step. "); if (array[middle] < key) first = middle + 1; else if (array[middle] == key) { index = middle; printf("%d found at location %d. ", key, middle+1); break; } else last = middle - 1; middle = (first + last)/2; } return index; } /** * Recursive linear search
  • 10. * Instead of for loop call same method with next index * first pass 0, check if key found at index 0, if not found call same method with index 1 ..... */ int linear_search_recursive(int array[],int key,int size,int index){ if(array[index] == key){ printf("%d found at location %d. ",key, index); return index; } else if (index >= size-1){ return -1; } else{ return linear_search_recursive(array,key,size,++index); } } /** * Recursive Binary Search * Recursively call Binary Search , check key found at element middle * if key == then return middle positon * if key > middle position , call recursive method for sub array range from [middle...last] * if key < middle position , call recursive method for sub array range from [0..middle] */ int binary_search_recursive(int array[],int key,int start,int end){ //Key not found if(start> end){ return -1; } int index = -1; int first = start; int last = end; int middle = (first+last)/2; //Print array between first nad last for each step printf("Start binary search step. "); for(int i = first ; i < last ; i++){ printf("Binary search step element.%d ",array[i]); }
  • 11. printf("Stop binary search step. "); if (array[middle] < key){ first = middle + 1; return binary_search_recursive(array,key,first,last) ; }else if (array[middle] == key) { printf("%d found at location %d. ", key, middle+1); return middle; } else{ last = middle - 1; return binary_search_recursive(array,key,first,last) ; } return -1; } /** *Function to sort the array * for Binary search we have to sort array first */ void sort(int number[], int size){ for (int i = 0; i < size; ++i) { for (int j = i + 1; j < size; ++j) { if (number[i] > number[j]) { int a = number[i]; number[i] = number[j]; number[j] = a; } } } } int main(int argc, char *argv[]) { int range = 100; int data[100];
  • 12. for(int i = 0 ; i < 100 ; i++){ int item = rand() % range + 1; data[i] = item; printf("array item %d : %d ",i,item); } sort(data,range); //search(data,120,100); //binary_search(data,41,0,99); //linear_search_recursive(data,41,100,0); binary_search_recursive(data,91,0,99); return 0; } Question 3 :- ------------------------------- To test with 1000 elements change the variable "range" , assign 1000 to it worst Time Complexity of Linear search is alwasy O(n), becuase we have to lop throug all elements in array For Binary search it is O(n/2) , but array shuld be sorted first Time complexity for Binaru Searc = Time Complexity ofSorting + Time complexity of Search Question 5 (Using Linked List):- -------------------------------- #include #include #include #include struct node { int data; int key; struct node *next; }; struct node *head = NULL; struct node *current = NULL; //display the list
  • 13. void printList() { struct node *ptr = head; printf(" [ "); //start from the beginning while(ptr != NULL) { printf("(%d,%d) ",ptr->key,ptr->data); ptr = ptr->next; } printf(" ]"); } //insert link at the first location void insertFirst(int key, int data) { //create a link struct node *link = (struct node*) malloc(sizeof(struct node)); link->key = key; link->data = data; if(current == NULL){ head = link; current = head; } else{ //append after head current->next = link; current = link; } } //is list empty bool isEmpty() { return head == NULL; } int length() {
  • 14. int length = 0; struct node *current; for(current = head; current != NULL; current = current->next) { length++; } return length; } //find a link with given key struct node* find(int key){ int index = -1; //start from the first link struct node* cur = head; //if list is empty if(head == NULL) { return NULL; } //navigate through list while( cur != NULL ){ if(cur->data == key){ index = cur->key; break; } //if it is last node if(cur->next == NULL){ index = -1; break; }else { //go to next link cur = cur->next; } } if(index == -1){ printf("element not found"); }
  • 15. else{ printf("element found at %d", index); } //if data found, return the current Link return current; } int main(){ int range = 100; for(int i = 0 ; i < 100 ; i++){ int item = rand() % range + 1; insertFirst(i,item); printf("array item %d : %d ",i,item); } struct node* search = find(84); return 0; }