Question

In: Computer Science

Hello, This is an Array Search Program. Details will be provided below and please don't hesitate...

Hello,

This is an Array Search Program. Details will be provided below and please don't hesitate to contact me if you need anything.

1- Brief Introduction:

Swapping Values

Swapping consecutive values in an array:

 ...   Before   After
       |---|    |---|
arr[2] | 8 |    | 1 |
       |---|    |---|
arr[3] | 1 |    | 8 |
       |---|    |---| 
 ...   
# Define an array, print the array before the swap
arr = [4, 0, 8, 1, 7]
print(arr)   # Output: [4, 0, 8, 1, 7]

# Use 2 for the example, the SWAP is probably in a loop though
idx = 2

# SWAP
(arr[idx], arr[idx + 1]) = (arr[idx + 1], arr[idx])

# Print the array after the swap
print(arr)   # Output: [4, 0, 1, 8, 7]

The first value on the right goes into the first on the left and the second value on the right goes into the second on the left.

For more details see the class notes on Tuples.

Be careful you don't subscript the array out of bounds.

Loops that access arr[idx + 1] must not let idx equal the last valid subscript.

2- Bubble sort:

We will sort least to greatest.

Bubble sort is often looked at because it is conceptually very simple.

To bubble sort do:

  • Go through the array and if the current element is greater than the one that immediately follows it, swap the two.

This will need to be done repeatedly, an element will move down in the array quickly but can only move up one array location in a single pass.

Pseudocode:

while ...
    while ...
        if the current element is > than the one that follows it
            swap the two

Be careful you don't subscript the array out of bounds.

3- What I mentioned above was some useful information, now here is what you need to do. Copy this program into python 3 and don't change the input values.

import random

# Input data size, validate the input, exit if bad
data_size = input('Please enter the number of data values: ')
if data_size.isdigit():
    data_size = int(data_size)
else:
    print("Exiting, input is not a number:", data_size)
    exit(1)

# Input upper limit of random value, validate the input, exit if bad
rand_limit = input('Please enter the upper limit for random values: ')
if rand_limit.isdigit():
    rand_limit = int(rand_limit)
else:
    print("Exiting, input is not a number:", rand_limit)
    exit(1)

# Input whether to show the random values, or not
show_data = input('Show the random data values, "y" if yes: ')

# Create empty data array
data = []

# Generate random numbers
ctr = 0
while ctr < data_size:
    rand_num = random.randrange(0, rand_limit)
    data.append(rand_num)
    
    # Output each random number if the user specified to
    if show_data == 'y':
        print(rand_num)

    ctr = ctr + 1

###################################################################
# ==== Search loop, count occurrences of user_input ====

# ==== Count the number of "mis-sorted" values ====

# ==== Bubble Sort ====

# ==== Count the number of "mis-sorted" values ====
4- please see the instructions that will guide you for the above copied program:

 Add code to the program in steps:
  1. Search, allow the user to search the list for an element and output the number of occurrences of that element.
  2. Count how many adjacent elements are out of order.
  3. Sort the array using the bubble sort.
  4. Count, repeat the step 2 code to verify that the array is sorted.

A section on each of the above follows.

Add code to your program in the above order.

1- search:

Write code that will repeatedly:

  • Get input from the user
  • If the input is not 'q' break out of the (outer) loop
  • Inner loop: search the array for occurrences of the user input and keep a count of them.
    • Compare each array element to the user input.
    • If an array element is the same as the user input increment a counter.
  • Output a count of the number of occurrences of the number the user input.

This will require nested loops.

  • The outer loop gets user input and breaks if the user is done searching.
  • The inner loop searches the array.

Run your code and make sure it performs correctly

Testing:

To test your code:

  • Print the array before the code to be tested
  • Print the array after the code to be tested
  • Use a small array size
  • Limit the upper random value so the numbers are a single digit.
    This is for easy visual inspection. You could limit to two digits also.

Remove any extra print statements.

2- Count the Adjacent Out of Order Elements:

Write code that compares each element of the array with the element immediately after.

Keep a count of how times an element was greater than the element immediately after.

Output the count found by the loop.

Be careful you don't subscript the array out of bounds.

Run your code and make sure it performs correctly.

To skip the "show random values" just type an enter/return. An empty string will be input which will not match the 'y'.
The same for the search.

DO NOT use the list count method.

3- sort: implement the bubble sort.

# Bubble Sort outline
while ...
    while ...
        if the current element is > than the one that follows it
            swap the two

For debugging the sort put print(data) before and after your sort code.

Run your code and make sure it performs correctly.

DO NOT use the list sort built-in function or method.

Finally, the last instruction to do:       

4- Count the Adjacent Out of Order Elements

Copy the code from step 2 and put it after the sort.

There should be 0 out-of-place adjacent values.

In general copying code in this manner is BAD.

When we can define functions we will be able to avoid this.

Run your code and make sure it performs correctly.

That's it! The problem is done here.

#NOTE: if you pick a value, let me know what value you picked. Please write the answer here so I can run it without typing it all over. Thank you very much.

Solutions

Expert Solution

# Input upper limit of random value, validate the input, exit if bad
rand_limit = input('Please enter the upper limit for random values: ')
if rand_limit.isdigit():
    rand_limit = int(rand_limit)
else:
    print("Exiting, input is not a number:", rand_limit)
    exit(1)

# Input whether to show the random values, or not
show_data = input('Show the random data values, "y" if yes: ')

# Create empty data array
data = []

# Generate random numbers
ctr = 0
while ctr < data_size:
    rand_num = random.randrange(0, rand_limit)
    data.append(rand_num)
    
    # Output each random number if the user specified to
    if show_data == 'y':
        print(rand_num)

    ctr = ctr + 1

#your code starts from here
while(input("Enter q to quit or any other key to continue"))!='q':
    search = input('Please enter the number to be searched: ')
    if search.isdigit():
        search = int(search)
    else:
        print("Exiting, input is not a number:", search)
        exit(1)
    count = 0
    for number in data:
        if number==search:
            count+=1
    print(count)


misplaced=0
for i in range(data_size-1):
    if data[i]>data[i+1]:
        misplaced+=1
print("misplaced = ",misplaced)

for i in range(data_size-1):
    for j in range(0, data_size-i-1):
        if data[j] > data[j+1]:
            data[j], data[j+1] = data[j+1], data[j]
print(data)

misplaced=0
for i in range(data_size-1):
    if data[i]>data[i+1]:
        misplaced+=1
print("misplaced = ",misplaced)

OUTPUT :


Related Solutions

// This program demonstrates a Binary Search, which search for a value // in an array,...
// This program demonstrates a Binary Search, which search for a value // in an array, assuming that the array is sorted in descending order. // You have to modify the function binarySearch() to search for a value // in an array that is sorted in ascending order. // NOTES: // Uncomment line 34 and comment line 32. You don't have to edit anything // else in the main(), just in the binarySearch() function. // EXAMPLES (using the array sorted...
Write a program that allows the user to search the array to find the number entered
Write a program that allows the user to search the array to find the number entered
HELLO CAN YOU PLEASE DO THIS JAVA PROGRAM WITH THE DIFFERNT CLASSES LISTED BELOW. I WILL...
HELLO CAN YOU PLEASE DO THIS JAVA PROGRAM WITH THE DIFFERNT CLASSES LISTED BELOW. I WILL LEAVE AWESOME RATING. THANK YOU IN ADVANCE. The code needed for this assignment has to somehow implement a stack interface (including a vector stack, array stack, and a linked stack). The classes needed are the Game class, the disk class, the driver, and the stack interface (including arraystack, linkedstack, and vectorstack) QUESTION Suppose you are designing a game called King of the Stacks. The...
// This program performs a linear search on a character array // Place Your Name Here...
// This program performs a linear search on a character array // Place Your Name Here #include<iostream> using namespace std; int searchList( char[], int, char); // function prototype const int SIZE = 8; int main() { char word[SIZE] = "Harpoon"; int found; char ch; cout << "Enter a letter to search for:" << endl; cin >> ch; found = searchList(word, SIZE, ch); if (found == -1) cout << "The letter " << ch      << " was not found in...
C++ PLEASE---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In this program, you will analyze an array
C++ PLEASE---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- In this program, you will analyze an array of 10 characters storing a gene sequence. You will be given a subsequence of 3 characters to look for within this array. If the subsequence is found, print the message: Subsequence <XXX> found at index <i>. Where i is the starting index of the subsequence in the array. Otherwise, print Subsequence <XXX> not found. The array of characters and the subsequence will be given through standard input. Read them and...
please go to details and don't forget to answer the questions that my professor ask for,...
please go to details and don't forget to answer the questions that my professor ask for, also explain for the first question in one paragraph and explain second question in one paragraph too. thanks. Sex Education and Teenage Pregnancy Santrock (2016) mentions in his text that the United States has one of the highest teenage pregnancy rates of industrialized nations, despite the fact that adolescent sexual activity is no higher in the United States. Why is that? For starters, sex...
Binary Search. Write a MIPS assembly program to perform a binary search on A[10], which is an array of 10 positive integers.
Binary Search. Write a MIPS assembly program to perform a binary search on A[10], which is an array of 10 positive integers. Your program should have a main routine that does the following:(a) Prompt the user to enter all the 10 integers in the array.(b) Prompt the user to enter the number to be searched.(c) Reads the integer values and makes sure it is a positive integer.(d) Prints the index of the integer. If the input is not available in...
Hello, please answer this question The nurse wants to search for information about a new medication...
Hello, please answer this question The nurse wants to search for information about a new medication that is in the testing phase of production. Which action should the nurse take when conducting a literature search about this medication? Select all that apply. A) Formulate a definition of the problem B) Ask a nurse colleague for help C) Identify the information D) Conduct a search of the most recent literature E) Skimming journal articles during lunch break
Hello, Please write this program in java and include a lot of comments and please try...
Hello, Please write this program in java and include a lot of comments and please try to make it as simple/descriptive as possible since I am also learning how to code. The instructions the professor gave was: Create your own class Your own class can be anything you want Must have 3 instance variables 1 constructor variable → set the instance variables 1 method that does something useful in relation to the class Create a driver class that creates an...
hello , could you please answer this question for me in details , my teacher want...
hello , could you please answer this question for me in details , my teacher want more than 400 word ?. it is an essay . 1) Discuss the application of Classical conditioning in reducing Anxiety.!!
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT