Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Python Code that creates a single dimensioned array of integers fills it with ra

ID: 3765857 • Letter: P

Question

Python Code that creates a single dimensioned array of integers fills it with random numbers, then sorts the array, and does searches in the array.

The program must first request the user to input an array size. This size may be any integer from 1 to 20,000 (make certain to verify that the number is within this range and if not, ask for a number again and again until you get a number if the correct range). Next the program will create an array of this size and fill the array with random numbers from 1 and the array size. Next it will copy this array into another array that your program crates that is the same size. The program then invokes a method that you will create that sorts the input array (but not the copied one). There is a sort routine on page 444 of your text. Next if the size of the array is 16 or less, the program will display the contents of both the sorted and unsorted arrays so that the sort routine can be verified.

Next the program will solicit a search number between 1 and array size from the user (make certain to verify that the number is within this range and if not, ask for a number again and again until you get a number if the correct range).

Next your program will invoke a method that uses a linear search. The method will return the position within the array (0 to array size less 1) if it finds the number. Otherwise it will return a minus one. The program will then display a message giving the location of the find or state that the number was not in the array.

Explanation / Answer

Completed tasks 1 and 3.


def sort(array):
   for i in range(len(array)):
       for j in range(len(array)-1):
           if(array[j] > array[j+1]):
               temp = array[j]
               array[j] = array[j+1]
               array[j+1] = temp
          
  
def find(array, search):
   for i in range(len(array)):
       if(array[i] == search):
           return i
   return -1

array = []
size = 0
while(size < 1 or size > 20000):
   size = int(input ("Enter size of array:"))
  
i = 0
while(i < size):
   val = int(input ("Enter integer:"))
   array.insert(i,val)
   i = i +1
  

unsortedArr = []
i = 0
while(i < size):
   unsortedArr.insert(i,array[i])
   i = i +1
  

sort(array)
if(size <= 16):
   print(unsortedArr)
   print(array)

num = 4
loc = find(array, num)
if(loc == -1):
   print(num," not found in the array ");
else:
   print(num," found at index: ",loc)

----------output--------------

Enter size of array:5
Enter integer:1
Enter integer:6
Enter integer:3
Enter integer:4
Enter integer:9
[1, 6, 3, 4, 9]
[1, 3, 4, 6, 9]
4 found at index: 2