mid1 prac sol
.pdf
keyboard_arrow_up
School
University of Maryland, College Park *
*We aren’t endorsed by this school
Course
351
Subject
Computer Science
Date
Dec 6, 2023
Type
Pages
4
Uploaded by DeanBaboonPerson1023
Kruskal
CMSC351: Practice Midterm 1
Fall 2023
These are practice problems for the upcoming midterm exam. You will be given a sheet of notes
for the exam.
Also, go over your homework assignments.
Warning:
This does not necessarily
reflect the length, difficulty, or coverage of the actual exam.
Problem 1. Assume that you are sorting an array of size
n
using Bubble Sort, where
n
= 2
k
−
1.
Assume that the smallest element is in the first location. The next two smallest elements are
in the next two locations in some order. The next four smallest elements are in the next four
locations in some order.
The next eight smallest elements are in the next eight locations in
some order. Etc. For example, assume
n
= 7 (and
k
= 3), the input might look like
10, 30, 20, 50, 70, 40, 60
The algorithm does not know this, and executes without this extra information.
(a) Assume that the elements within each group are in reverse order. For example, if
n
= 7
(and
k
= 3), the input will look like
10, 30, 20, 70, 60, 50, 40
What is the number of exchanges? Get the exact answer as a function of
k
, and the exact
high order term as a function of
n
. Show your work.
Solution:
Since
n
= 2
k
−
1, we know that
k
= lg(
n
+ 1).
We know from class that the worst case number of exchanges for Bubble Sort on a list
of size
m
is (
m
−
1)
m/
2. We can treat each group as an independent Bubble Sort.
This gives
k
−
1
X
i
=0
(2
i
−
1)2
i
2
=
1
2
4
k
−
1
4
−
1
−
1
2
(2
k
−
1) =
1
2
(2
k
)
2
−
1
3
−
1
2
(2
k
−
1)
=
1
2
(
n
+ 1)
2
−
1
3
−
1
2
((
n
+ 1)
−
1) =
n
(
n
−
1)
6
(b) Assume that the elements within each group are in random order. What is the average
number of exchanges? Get the exact answer as a function of
k
, and the exact high order
term as a function of
n
. Show your work.
Solution:
We know from class that the average case number of exchanges for Bubble
Sort on a list of size
m
is (
m
−
1)
m/
4. We can treat each group as an independent
Bubble Sort. This gives
k
−
1
X
i
=0
(2
i
−
1)2
i
4
=
1
4
4
k
−
1
4
−
1
−
1
4
(2
k
−
1) =
1
4
(2
k
)
2
−
1
3
−
1
4
(2
k
−
1)
=
1
4
(
n
+ 1)
2
−
1
3
−
1
4
((
n
+ 1)
−
1) =
n
(
n
−
1)
12
Kruskal
CMSC351: Practice Midterm 1
Fall 2023
Problem 2. Assume you have an array of numbers, where each value occurs
at most
twice.
We
consider sums of contiguous numbers in the array. But we only consider such sums whose two
endpoints have the same value. The sum includes the two equal values themselves. So if the
two equal numbers are at index
i
and index
j
(
i < j
) in array
A
, then we sum all the values
A
[
i
]
, A
[
i
+ 1]
, . . . , A
[
j
].
(a) Give an algorithm that finds the maximum such sum. Make your algorithm as efficient as
possible. Describe the algorithm briefly in English
and
in psuedo code.
(b) Analyze the running time of your algorithm.
Problem 3. Let
A
[1
, .., n
] be an array of
n
numbers (some positive and some negative).
(a) Give an algorithm to find which two numbers have sum closest to zero.
Make your
algorithm as efficient as possible. Write it in pseudo-code.
(b) Analyze its running time.
Problem 4. Assume the you have a heap of size
n
= 2
m
−
1 (stored in an array).
(The largest
element is at the root.)
You may describe the following algorithms in high level language, but
they
must
be clear. Give your answers as a function of
n
. You may assume
n
is large. You
may use extra memory.
(a) Give an algorithm, minimizing the number of comparisons, to find the smallest element
in the heap. Exactly how many comparisons does it take.
(b) Give an algorithm, minimizing the number of comparisons, to find the second smallest
element in the heap. Exactly how many comparisons does it take.
(c) Give an algorithm, minimizing the number of comparisons, to find the third smallest
element in the heap. Exactly how many comparisons does it take.
Problem 5. Consider the following algorithm for finding the two smallest elements in a list: Sort
the first two elements. Call them
special
. Then iterate through the remainder of the elements
one at a time. First compare each new element to the larger of the two special elements, and
if necessary compare it to the smaller. The two new special elements will be the smallest two
of those three elements.
(a) Write the pseudocode for this algorithm.
(b) What is the exact best case number of comparisons? Justify and simplify.
Solution:
n
−
1
(c) What is the exact worst case number of comparisons? Justify and simplify.
Solution:
2
n
−
3
Page 2 of 4
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
The Problem: Matching Group Schedules
The group schedule matching takes two or more arrays as input. The arrays represent slots that are already booked and the login/logout time of group members. It outputs an array containing intervals of time when all members are available for a meeting for a minimum duration expected.
Sample Input
Enter person1_Schedule =[[ ‘7:00’, ’8:30’], [’12:00’, ’13:00’], [’16:00’, ’18:00’]]
person1_DailyAct = [‘9:00’, ’19:00’]
Enter person2_Schedule = [[ ‘9:00’, ’10:30’], [’12:20’, ’13:30’], [’14:00’, ’15:00’], [’16:00’, ’17:00’ ]]
person2_DailyAct = [‘9:00’, ’18: 30’]
Enter duration_of_meeting =30
Sample output
[[’10:30’, ’12:00’], [’15:00’, ’16:00’], [’18:00’, ’18:30’]]
Implementation
Have following files
Project1_starter.py or project1_starter.cpp that defines functions for the algorithm described above. You will need to develop and write the functions. Describe how to run your program in the ReadMe file
Input.txt containing the sample input…
arrow_forward
True or False
For each statement below, indicate whether you think it is True or False
If you have an array with no “holes”, the append function performs at O(1)
Inserting an element at the front and shifting all elements performs significantly worse than appending an element at the end of the list
For the insert function, if the array is empty, there are no comparison operations that need to be performed and you can immediately add the new element
Binary search can be used on an unsorted array to significantly improve its performance from O(n) to O(1)
Because the update algorithm depends on using linear search, its performance is O(1) in the worst case scenario
True
If you search for and delete an element in an unsorted array and then shift the rest of the elements to fill the hole, the worst case performance is O(n)
If you search for and delete an element in an unsorted array and then move the last element to fill the hole, the worst case performance is O(n)
arrow_forward
True or False
For each statement below, indicate whether you think it is True or False
If you have an array with no “holes”, the append function performs at O(1)
Inserting an element at the front and shifting all elements performs significantly worse than appending an element at the end of the list
For the insert function, if the array is empty, there are no comparison operations that need to be performed and you can immediately add the new element
Binary search can be used on an unsorted array to significantly improve its performance from O(n) to O(1)
arrow_forward
This is not a graded question so please don't disregard it as if it is. Thank you in advance professor!
arrow_forward
Median Function – In statistics, the median of a set of values is the value that lies in the middle when the values are arranged in sorted order. If the set has an even number of values, the median is the average of the two middle values.
Your program should start with two arrays of integers containing the following values:
Even numbered array: 17 32 45 68 99 101 67 89 22 27
Odd numbered array: 17 32 45 68 99 101 67 89 22
Using a sort function of your choice, first sort the arrays. NOTE: you may use the Standard Template Library sort function or your own sort function.
Then, write a function that determines the median of a sorted array. The function should take an array of numbers and an integer indicating the size of the array and return the median of the values in the array. The same function should be called twice – once for the even array and once for the odd array.
Your program should also have a printArray function that can be used to print the sorted array. (It…
arrow_forward
Matrix size 10 * 10 You want to print the elements that fall in the four corners of the array. Choose one of the options:
arrow_forward
Task4:
Array Based List using Pointers Task
Let's say you have a sorted array:
int array_list[6] = [2,4,5,6,7,8]
You are given a target value. You need to find two numbers whose addition is equal to target
value.
Example:
array_list = 2,4,5,6,7,8
target = 15
Output = 7, 8
NOTE: You have to use pointers only.
arrow_forward
Array TypesObjective: Based on the given values and initializations, give what is being required of each statement.1. Given A[10], α=2000, esize=4 bytes:a) Find the number of elements.b) Find the address of the 6th element.c) Find the index no. of the 8th element.2. Given E[3][4], α=2020, esize=4 bytes:a) Find the total no. of elements.b) Find the address of the last element.c) Find the address of the 10th element.
arrow_forward
Task 3: Statistics using arrays:
by java programming
With the spread of COVID 19, the HR department in a company has decided to conduct some statistics
among the employees in order to determine the number of infections according to some conditions.
For each employee, they have to record the code, name, age, whether he/she was infected or no and
the remaining days of leaves for him/her.
You are requested to write the program that maintains the lists of details for the employees as
mentioned above using the concept of arrays. The program repeats the display of a menu of services
until the user decides to exit.
1. Start by initializing the employee details by reading them from the keyboard.
2. Repeat the display of a menu of 4 services, perform the required task according to the user’s
choice and asks the user whether he/she wants to repeat or no. You need to choose one service
from each category (‘A’,’B’,’C’,’D’)
a. A. Display the total number of employees that were infected
b. B.…
arrow_forward
Section A: Multiple Choice Questions
Q6: The quicksort is being used to sort an array in the ascending order. Which one of the following is not true ?
a) All the elements in the left subarray are less than or equal to the pivot
b) All the elements in the right subarray are larger than the pivot
c) The pivot is placed between the two subarrays
d) All the elements in the right subarray are less than or equal to the pivot
arrow_forward
Assume the array is sorted according to the roll number.
Jonny, as a school teacher conducted the test in the class and students submitted responses along with time duration to complete the test. Now your task is to find the student number who taken the most time.
In kotlin
arrow_forward
Find primes
This program creates and displays a 5x10 matrix(5 rows and 10 columns) of random integers between 1 and a maximum value(user input).
Hint: Use the random library to generate each number and place it into your 2D list.
The program then counts the number of prime numbers in each row of the array and displays this number, along with the found primes.
The program finally displays the total number of prime numbers in the matrix.
arrow_forward
Programming Language: C++
You have been hired by Google to work on their YouTube videos search team. Every YouTube video has a unique ID and those IDs are in unsorted order. As a software engineer, you are required to make a YouTube search engine which works for very user. Create a test engine that only holds seven YouTube IDs. Prompt for and get from the user the seven IDs and store them in an integer array. Then sort and print the array using the insertion sort algorithm. Finally, use a sentinel loop to prompt for and get from the user a series of IDs. For each ID, perform a binary search on the array and tell the user if it was found or not. If found, print the index where the ID is stored. Continue to prompt the user for an ID until entering the sentinel value of -999.
In addition to function main, define the following two functions:
void insertion_sort(int arr[], int arr_size)
int binary_search(int sort_arr[], int size_array, int search_value)
binary_seacrh returns…
arrow_forward
=' =Trace bucket sort algorithm as it sorts the array into an ascending order.
ASSUMPTION: (1) Use four buckets that have the ranges specified as follows:
%3D
[0,25), [25,50), [50,75), and [75,100), respectively
(2) Show (or explain) the steps as detail as possible.
If needed, please illustrate the steps.
A =[ 78
17
39
26
72
94
21
12
68 ]
29
arrow_forward
Problem2: 2D Arrays
Define a 2D array using Java code that takes from a teacher the total number of rows and the
total number of columns. Then let the teacher fill the array by students IDs and courses marks
for each student. And print the following:
1- Print the array.
2- Print the marks that are less than 50 (mark < 50)
arrow_forward
Individual Exercise: Sieve of Eratosthenes
O The Sieve of Eratosthenes is a technique for finding all the prime numbers up to a given last number.
o It can be implemented as a program by using the algorithm (steps) given below.
" Create a variable for the last number initialized as 100 etc. (e.g., int lastNumber = 100;)
• Create a boolean array isPrime[] to keep track of which numbers up to lastNumber are prime.
O The length of the array must be equal to lastNumber + 1 as the array indexes start from zero.
o Note: The default value is false for all the array elements when a boolean array is created by using new.
' Set all the array elements beginning from index = 2 (the first prime number) to true.
' Outer loop: Repeat the following steps for each number num within 2 <= num <= lastNumber / num.
o if isPrime[num] is true (meaning that num is prime as no factors exist for num):
" Inner loop: Set the isPrime[] elements for all the multiples of num to false.
O When the nested loop ends,…
arrow_forward
q3
=
range (30)
# change q3 to a np.array
# add 1 to each element in q3
# add 2 to the last 5 elements in q3
# subtract 10 to the first element in q2
arrow_forward
8. Repetition Use Python Language
Write a method that takes in an array as a
parameter and counts the repetition of
each element. That is, if an element has
appeared in the array more than once, then
its 'repetition' is its number of occurrences.
The method returns true if there are at least
two elements with the same number of
'repetition'. Otherwise, return false.
Input: {4,5,6,6,4,3,6,4} Output: True
Explanation: Two numbers repeat in this
array: 4 and 6. 4 has a repetition of 3, 6
has a repetition of 3. Since two numbers
have the same repetition output is True.
Input: {3,4,6,3,4,7,4,6,8,6,6} Output: False
Explanation: Three numbers repeat in this
array:3,4 and 6 .3 has a repetition of 2, 4
has a repetition of 3, 6 has a repetition of 4.
Since no two numbers have the same
repetition output is False.
arrow_forward
Alphabet Random Walk• Write a program to generate a random walk that spans a 10*10 character array (The initial values of the elements are all.). The program must randomly walk from one element to another, moving one element position up, down, left or right each time. The elements that have been visited are labeled with the letters A through Z in the order in which they were visited
arrow_forward
C Program / C Language
Make a C program of the array .
arrow_forward
ARRAY RANDOMIZER
Create a program that shuffels all the elements present in an array. To shuffle an array, you need to do at
least 500 random swaps of any elements in the array given below. Print the shuffled array in the output.
{12, 54, 22, 100, -3, 5, 10, -33, 78, 90, 29, -45, 77, -9, 19, 21}
Language: CPP
arrow_forward
4
arrow_forward
DESIGN YOUR OWN SETTING
Task 5: Devise your own setting for storing and searching the data in an array of non-negative integers redundantly. You may just describe the setting without having to give an explicit algorithm to explain the process by which data is stored. You should explain how hardware failures can be detected in your method. Once you have described the setting, complete the following:
Write a pseudocode function to describe an algorithm where the stored data can be searched for a value key: if the data is found, its location in the original array should be returned; -1 should be returned if the data is not found; -2 should be returned if there is a data storage error
Include a short commentary explaining why your pseudocode works
Describe the worst-case and best-case inputs to your search algorithm
Derive the worst-case and best-case running times for the search algorithm
Derive the Theta notation for the worst-case and best-case running times
Maximum word…
arrow_forward
Multi Dimensional Activity
Client Requirement:
The customer wants a program that will ask the user to enter 2 numbers. these numbers will then be stored in the first two columns. the cycle will repeat until the 5 by 2 array will be completed. then the values will be prompted for checking.
arrow_forward
C Program/ C Language
Make a C program for the array. Enter a bunch of integers then it should print the largest sum of a strictly ascending sequence of the array. A strictly ascending sequence is a sequence where the current number is always lesser than the next number.
arrow_forward
When the values of an array are stored in ascending order, they are stored from greatest to least.
arrow_forward
C++ language
Write a program that asks the user to enter daily sale for five stores and record them in an array.The program should then display a bar graph comparing each store’s sales for all days of a week.Create each bar in the bar graph by displaying a row of asterisks. Each asterisk should representRs.1000 of sales. The program also calculates the total sale each day, and total sale of the week.Here is an example of the program s output.Enter day 1 sales for store 1: 4000 [Enter]Enter day 1 sales for store 2: 6000 [Enter]Enter day 1 sales for store 3: 10000 [Enter]Enter day 1 sales for store 4: 11000 [Enter] Enter day 1 sales for store 5: 3000 [Enter]Enter day 2 sales for store 1: 9000 [Enter]Enter day 2 sales for store 2: 8000 [Enter]Enter day 2 sales for store 3: 19000 [Enter]Enter day 2 sales for store 4: 7000 [Enter]Enter day 2 sales for store 5: 9000 [Enter]…(and so on.)Weekly SaleMonday: Total Sale: 34,000/-Store 1: **** (4000)Store 2: ****** (6000)Store 3: **********…
arrow_forward
Java:
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
Programming with Microsoft Visual Basic 2017
Computer Science
ISBN:9781337102124
Author:Diane Zak
Publisher:Cengage Learning
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage
Related Questions
- The Problem: Matching Group Schedules The group schedule matching takes two or more arrays as input. The arrays represent slots that are already booked and the login/logout time of group members. It outputs an array containing intervals of time when all members are available for a meeting for a minimum duration expected. Sample Input Enter person1_Schedule =[[ ‘7:00’, ’8:30’], [’12:00’, ’13:00’], [’16:00’, ’18:00’]] person1_DailyAct = [‘9:00’, ’19:00’] Enter person2_Schedule = [[ ‘9:00’, ’10:30’], [’12:20’, ’13:30’], [’14:00’, ’15:00’], [’16:00’, ’17:00’ ]] person2_DailyAct = [‘9:00’, ’18: 30’] Enter duration_of_meeting =30 Sample output [[’10:30’, ’12:00’], [’15:00’, ’16:00’], [’18:00’, ’18:30’]] Implementation Have following files Project1_starter.py or project1_starter.cpp that defines functions for the algorithm described above. You will need to develop and write the functions. Describe how to run your program in the ReadMe file Input.txt containing the sample input…arrow_forwardTrue or False For each statement below, indicate whether you think it is True or False If you have an array with no “holes”, the append function performs at O(1) Inserting an element at the front and shifting all elements performs significantly worse than appending an element at the end of the list For the insert function, if the array is empty, there are no comparison operations that need to be performed and you can immediately add the new element Binary search can be used on an unsorted array to significantly improve its performance from O(n) to O(1) Because the update algorithm depends on using linear search, its performance is O(1) in the worst case scenario True If you search for and delete an element in an unsorted array and then shift the rest of the elements to fill the hole, the worst case performance is O(n) If you search for and delete an element in an unsorted array and then move the last element to fill the hole, the worst case performance is O(n)arrow_forwardTrue or False For each statement below, indicate whether you think it is True or False If you have an array with no “holes”, the append function performs at O(1) Inserting an element at the front and shifting all elements performs significantly worse than appending an element at the end of the list For the insert function, if the array is empty, there are no comparison operations that need to be performed and you can immediately add the new element Binary search can be used on an unsorted array to significantly improve its performance from O(n) to O(1)arrow_forward
- This is not a graded question so please don't disregard it as if it is. Thank you in advance professor!arrow_forwardMedian Function – In statistics, the median of a set of values is the value that lies in the middle when the values are arranged in sorted order. If the set has an even number of values, the median is the average of the two middle values. Your program should start with two arrays of integers containing the following values: Even numbered array: 17 32 45 68 99 101 67 89 22 27 Odd numbered array: 17 32 45 68 99 101 67 89 22 Using a sort function of your choice, first sort the arrays. NOTE: you may use the Standard Template Library sort function or your own sort function. Then, write a function that determines the median of a sorted array. The function should take an array of numbers and an integer indicating the size of the array and return the median of the values in the array. The same function should be called twice – once for the even array and once for the odd array. Your program should also have a printArray function that can be used to print the sorted array. (It…arrow_forwardMatrix size 10 * 10 You want to print the elements that fall in the four corners of the array. Choose one of the options:arrow_forward
- Task4: Array Based List using Pointers Task Let's say you have a sorted array: int array_list[6] = [2,4,5,6,7,8] You are given a target value. You need to find two numbers whose addition is equal to target value. Example: array_list = 2,4,5,6,7,8 target = 15 Output = 7, 8 NOTE: You have to use pointers only.arrow_forwardArray TypesObjective: Based on the given values and initializations, give what is being required of each statement.1. Given A[10], α=2000, esize=4 bytes:a) Find the number of elements.b) Find the address of the 6th element.c) Find the index no. of the 8th element.2. Given E[3][4], α=2020, esize=4 bytes:a) Find the total no. of elements.b) Find the address of the last element.c) Find the address of the 10th element.arrow_forwardTask 3: Statistics using arrays: by java programming With the spread of COVID 19, the HR department in a company has decided to conduct some statistics among the employees in order to determine the number of infections according to some conditions. For each employee, they have to record the code, name, age, whether he/she was infected or no and the remaining days of leaves for him/her. You are requested to write the program that maintains the lists of details for the employees as mentioned above using the concept of arrays. The program repeats the display of a menu of services until the user decides to exit. 1. Start by initializing the employee details by reading them from the keyboard. 2. Repeat the display of a menu of 4 services, perform the required task according to the user’s choice and asks the user whether he/she wants to repeat or no. You need to choose one service from each category (‘A’,’B’,’C’,’D’) a. A. Display the total number of employees that were infected b. B.…arrow_forward
- Section A: Multiple Choice Questions Q6: The quicksort is being used to sort an array in the ascending order. Which one of the following is not true ? a) All the elements in the left subarray are less than or equal to the pivot b) All the elements in the right subarray are larger than the pivot c) The pivot is placed between the two subarrays d) All the elements in the right subarray are less than or equal to the pivotarrow_forwardAssume the array is sorted according to the roll number. Jonny, as a school teacher conducted the test in the class and students submitted responses along with time duration to complete the test. Now your task is to find the student number who taken the most time. In kotlinarrow_forwardFind primes This program creates and displays a 5x10 matrix(5 rows and 10 columns) of random integers between 1 and a maximum value(user input). Hint: Use the random library to generate each number and place it into your 2D list. The program then counts the number of prime numbers in each row of the array and displays this number, along with the found primes. The program finally displays the total number of prime numbers in the matrix.arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- Programming with Microsoft Visual Basic 2017Computer ScienceISBN:9781337102124Author:Diane ZakPublisher:Cengage LearningEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENTProgramming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:Cengage
Programming with Microsoft Visual Basic 2017
Computer Science
ISBN:9781337102124
Author:Diane Zak
Publisher:Cengage Learning
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Programming Logic & Design Comprehensive
Computer Science
ISBN:9781337669405
Author:FARRELL
Publisher:Cengage