Question

This is an assignment for my algorithm class which I have written the code partially and...

This is an assignment for my algorithm class which I have written the code partially and only need to complete it by adding a time function that calculates the average running time. We could use any programming language we want so I am using C++. I am including the instruction and my partial code below. Thank you!

Implement linearSearch(a,key) and binarySearch( a,key)functions.

Part A.In this part we will calculate theaverage-case running time of each function.1.Request the user to enter a positive integer, and call it n.(n =10^5)

2.Generate n random integers between -1000 to 1000 and save them in array a.(You can userandifunction in MATLAB)

3.Sort a(you can use any sorting algorithm you want. If you are using MATLAB, you can call the sortfunction to sort your numbers)

4.Pick a random number in a and save it in variable called key.

5.Call each function separately to search for the keyin the given array.

6.To calculate the average-running time, you need to have a timer to save the total runtime wherepeating step 4 and 5 for 500 times.(tic toc in MATLAB)(Note1:Do not forget to divide the runtime by the number of the times you run step 4-5)

(Note2: Remember to choose a different random number each time you go back to step 4.)

Part B.In this part wewillcalculate theworst-case running timeof each function.

1.Repeat steps1 to 3 inpart A.

2.Now to have theworst case scenario, set the value of the key to 5000 to make sure it does not exist in the array.

3. Run each function once to calculate the worst - case running time when n=10^5.

4.Calculate how much time your machine takes to run one single step.

5.Now estimate theworst-case running time for each algorithm when n = (10^7).

(we've been told to use a hint from homework 3 but there was no information to be found on the homework 3, you can just ignore that part of the queation as I've talked to the instructor)

6.Nowrepeat step 1-3 forn = 10^7 and compare the actual running time with your answer in step 5

=====================

My Partial code:

//Rojin Shahbazian

#include

#include

#include

#include

#include

#include

#include

using namespace std;

const int N = pow(10,5);

int key;

bool LinearSearch(int a[],int key);

bool BinarySearch(int a[], int key)

{

/*

int minimum=0;

int maximum= N -1;

int mid = (minimum + maximum)/2;

bool found = false;

if( a[mid] == key)

{

cout<<" The number was found in array index : " << mid<

found = true;

}

  

else

{

if (key > a[mid])

{

minimum = mid+1;

mid =(minimum + maximum)/2;

while(!found && minimum < maximum)

{

if (key == a[mid])

found = true;

else if (key > a[mid])

{

minimum = mid+1;

mid =(minimum + maximum)/2;

}

else if (key < a[mid])

{

maximum = mid -1;

mid =(minimum + maximum)/2;

}

}

  

}

else

{

maximum = mid -1;

mid =(minimum + maximum)/2;

while(!found && minimum < maximum)

{

if (key == a[mid])

found = true;

else if (key > a[mid])

{

minimum = mid+1;

mid =(minimum + maximum)/2;

}

else if (key < a[mid])

{

maximum = mid -1;

mid =(minimum + maximum)/2;

}

}

}

}

return found;

   */

int minimum=0;

int maximum= N;

  

bool found = false;

while(minimum <= maximum && !found)

{

int mid = (minimum + maximum)/2;

if (key == a[mid])

found = true;

else if (key> a[mid])

minimum = mid +1;

else

maximum = mid -1;

}

return found;

  

}

/*void Sorted()

{

int array[n];

sort(array, array+n);

}

*/

/*

void merge( int array[n], int l, int m, int r)

{

int i, j, k;

int n1 = m-l+1;

int n2 = r-m;

int L[n1], R[n2];

for(i=0; i

L[i] = array[l+i];

for(j=0; j

R[j] = array[m+1+j];

i=0;

j=0;

k=l;

while(i

{

if(L[i]<=R[j])

{

array[k]= L[i];

i++;

}

else

{

array[k]=R[j];

j++;

}

k++;

}

while(i

{

array[k] = L[i];

i++;

k++;

  

}

while(j

{

array[k] = R[j];

j++;

k++;

  

}

}

void mergeSort(int array[], int l, int r)

{

if(l

{

int m = l+(r-l)/2;

mergeSort(array, l, m);

mergeSort(array, m+l, r);

merge(array, l, m, r);

}

}

*/

int main()

{

int array[N];

int min = 2000;

int max = -1000;

srand(time(NULL));

for(int i = 0; i<=N; i++)

{

array[i]= rand()% min+max;

cout<

}

int randIndex = rand()%N;

sort(array,array+N+1);

for(int i = 0; i<=N; i++)

{

cout<

}

int key = array[randIndex];

cout<<"The randomly picked number is: "<

  

cout<

cout<

  

  

int array1[N];

srand(time(NULL));

for(int i = 0; i<=N; i++)

{

array1[i]= rand()% min+max;

cout<

}

sort(array1,array1+N+1);

for(int i = 0; i<=N; i++)

{

cout<

}

int key1 = 5000;

cout<<"The key is: "<

  

cout<

cout<

  

  

}

bool LinearSearch(int a[],int key)

{

bool found = false;

int count = 0;

while(!found && count<=N)

{

if (a[count] == key)

found = true;

else

++count;

}

return found;

  

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Since you are allowed to do in any Language , I am writing this program in JAVA.

Output shots are given after program.

import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
public class Performance {
  
public static void linearSearch(int arr[],int k){
int flag=0;
long linearTime=System.nanoTime();
for(int i=0;i<arr.length;i++){
if(arr[i]==k){
System.out.println("Found the element at "+ (i+1));
flag=1;
}
}
long linearTimeEnd=System.nanoTime();
if(flag==0)
System.out.println("Element not found of Linear search ");
System.out.println("Time Taken by Linear Search in ms(millisecond) = "+(-linearTime+linearTimeEnd)+"ns");
  
}
public static void binarySearch(int arr[],int k){
int i=0,j=arr.length-1;
int flag=0;
long Time=System.nanoTime();
while(i<=j){
int mid=(i+j)/2;
if(arr[mid]==k)
{
System.out.println("Found the element at "+ (mid+1));
flag=1;
}
else if(arr[mid]>k)
j=mid-1;
else
i=mid+1;
}
long End=System.nanoTime();
if(flag==0)
System.out.println("Element not found of binary search ");
System.out.println("Time Taken by Binary Search in ns(nanosecond) = "+(-Time+End)+"ns");
}
public static void main(String args[]) {
Scanner in=new Scanner(System.in);
System.out.println("Enter the size of the Arrays : ");
int n=in.nextInt();
int arr[]=new int[n];
int min=-1000,max=1000;
for(int i=0;i<n;i++){
int randomNum=(int)(Math.random() * ((max - min) + 1)) + min;
arr[i]=randomNum;
}
System.out.println("Enter the key to be searched : ");
int k=in.nextInt();
  
System.out.println("For "+n+" inputs :");
  

linearSearch(arr,k);

  
  
long sortTimeStart=System.nanoTime();
Arrays.sort(arr);
long sortTimeEnd=System.nanoTime();
System.out.println("Time Taken by Sorting in ns(nanosecond) = "+(-sortTimeStart+sortTimeEnd)+"ns");
  
  
  
binarySearch(arr,k);

  

}
}

Bluel: Terminal Window - Assignment Options Enter the size of the Arrays: 100000 Enter the key to be searched: 5000 For 10000

Bluel: Terminal Window - Assignment Options Enter the size of the Arrays: 10000000 Enter the key to be searched: 5000 For 100

Add a comment
Know the answer?
Add Answer to:
This is an assignment for my algorithm class which I have written the code partially and...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • How would I be able to get a Merge Sort to run in this code? MY...

    How would I be able to get a Merge Sort to run in this code? MY CODE: #include <iostream> #include <fstream> #include <stdlib.h> #include <stdio.h> #include <time.h> using namespace std; class mergersorter { private:    float array[1000] ;    int n = 1000;    int i=0; public:    void fillArray()    {        for(i=1;i<=n;i++)        {            array[i-1]= ( rand() % ( 1000) )+1;        }    }    void arrayout ()    {   ...

  • Merge Sort: Time Complexity: O(n log(n)) #include "stdafx.h" #include <iostream> #include <time.h> #include <stdlib.h> using namespace...

    Merge Sort: Time Complexity: O(n log(n)) #include "stdafx.h" #include <iostream> #include <time.h> #include <stdlib.h> using namespace std; void combine(int *a, int low, int high, int mid) {        int i, j, k, c[100000];        i = low;        k = low;        j = mid + 1;        while (i <= mid && j <= high)        {               if (a[i] < a[j])               {                      c[k] = a[i];                      k++;                      i++;               }               else               {                     ...

  • In this assignment you will implement merge-sort algorithm by creating 2 threads instead of 2 pro...

    In this assignment you will implement merge-sort algorithm by creating 2 threads instead of 2 processes. First half of the array will be sorted by thread 1 and the second half by thread 2. When the threads complete their tasks, the main program will merge the half arrays. You should not waste your time on merge-sort algorithm. Use the merge sort algorithm given below void mergesort(int a[],int i,int j) { int mid; if(i<j) { mid=(i+j)/2; mergesort(a,i,mid); //left recursion mergesort(a,mid+1,j); //right...

  • Hello, I want to check if my C++ code is correct and follows the requeriments described...

    Hello, I want to check if my C++ code is correct and follows the requeriments described thanks. Requeriments: Assignment Sorting Benchmark each of the sorting methods listed below. Insertion Sort Bubble Sort Selection Sort Heap Sort. Quick Sort. Merge Sort. Benchmark each of the above sorting methods for data sizes of 10000, 20000, 30000, 40000 and 50000. Display the results in a table as shown below. The table should have rows and columns. However, the rows and columns need not...

  • use the same code. but the code needs some modifications. so use this same code and...

    use the same code. but the code needs some modifications. so use this same code and modify it and provide a output Java Program to Implement Merge Sort import java.util.Scanner Class MergeSort public class MergeSort Merge Sort function / public static yoid sortfintfl a, int low, int high) int N-high-low; if (N1) return; int mid- low +N/2; Il recursively sort sort(a, low, mid); sort(a, mid, high); I/ merge two sorted subarrays int] temp new int[N]; int i- low, j-mid; for...

  • Hello, I need help with my code. The code needs to display random number from 1...

    Hello, I need help with my code. The code needs to display random number from 1 to 50 every time the program runs but the program displays the same random numbers every time. Thanks #include #include using namespace std; void dynAlloc(int size, int *&arr); void displayArray(int *arr, int n); void insertionSort(int *arr, int n, int *temp); void linear_search(int *arr, int n, int key); void binary_search(int *arr, int n, int key); int main() {   const int n = 50; int *arr,...

  • So. I'm sick and I need help figuring out whatever is going on with this. #include...

    So. I'm sick and I need help figuring out whatever is going on with this. #include using namespace std; //prototypes int getExchangesInBubbleSort(int[], int); int getExchangesInSelectionSort(int[], int); int main() {    char choice;       cout << "1. Search Benchmarks\n";    cout << "2. Sorting Benchmarks\n";    do    {        int input;        cout << "Please enter the program you would like to run. \n";        cin >> input;               if (input == 1)...

  • Please I am in a hurry, I need an answer asap. I have seen an answer previously regarding to this...

    Please I am in a hurry, I need an answer asap. I have seen an answer previously regarding to this question, however I found a lot of mistakes on it, where the guy declared a public class, which is not a thing in C language. Furthermore it is important to divide the question into two C files, one for part a and one for part b. hw2 Merge Sort algorithm using 2 processes a.) Define an integer array of 100...

  • Any help in the compiler error //Driver Program //***************** /** * * CSCI 241 Assignment 8...

    Any help in the compiler error //Driver Program //***************** /** * * CSCI 241 Assignment 8, Part 3 * * Author: your name * z-ID: your z-ID * Date: due date of assignment * * This program builds, sorts and prints lists using the quicksort and * merge sort algorithms. */ #include <iostream> #include <iomanip> #include <vector> #include <string> #include "sorts.h" #include "quicksort.h" #include "mergesort.h" using std::cout; using std::fixed; using std::left; using std::setprecision; using std::string; using std::vector; // Data files...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT