SlideShare a Scribd company logo
1 of 15
Download to read offline
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

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
 
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
 
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
 
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
 
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
 
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
 
SlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.pdfSlideSet_4_Arraysnew.pdf
SlideSet_4_Arraysnew.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
 
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
 
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
 
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
 
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
 

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

Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111Details on CBSE Compartment Exam.pptx1111
Details on CBSE Compartment Exam.pptx1111
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Simple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdfSimple, Complex, and Compound Sentences Exercises.pdf
Simple, Complex, and Compound Sentences Exercises.pdf
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 

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; }