Assignment #7 [2%]
Chapter 8: Searching and Sorting Arrays
Other Instructions will be provided by the instructor
Question 1: Pseudo code and Programming
Given the following array, write a pseudo code and program to sort the array using a selection
sort and display the number of scores that are less than 500 and those greater than 500.
Scores[0] = 198 Scores[1] = 486 Scores[2] = 651
Scores[3] = 85 Scores[4] = 216 Scores[5] = 912
Scores[6] = 73 Scores[7] = 319 Scores[8] = 846
Scores[9] = 989
Answer:
def selectionSort(score):
for l in range(len(score)):
min = l
for i in range(l + 1, len(score)):
if score[i] < score[min]:
min = i
temp=score[l]
score[l]=score[min]
score[min]=temp
print("Scores less than 500:")
for j in range(len(score)):
if score[j] < s:
print(score[j])
print("Score greater than 500:")
for j in range(len(score)):
if score[j] > s:
print(score[j])
return(score)
score=[198,486,651,85,216,912,73,319,846,989]
s=500
selectionSort(score)
Pseudo Code:
Declare score as array
Declare s,i,l,j as integer
set n as length of array
for (l=0;l<n-1;l++)
min=l
for (i=l+1;i<n;i++):
if score[i]<score[min]
min=i
temp=score[l]
score[l]=score[min]
score[min]=temp
write score less than 500:
for (j=0;j<n;j++)
if score[j]>s
write score[j]
write score less than 500
for (j=0;j<n;j++)
if score[j]<s
write score[j]
selectionSort(score)
Question 2: Programming
Write a program to load an array, Squares, with 100 numbers. Each element should contain the
square of its index value. In other words, Squares[0] = 0, Squares[3] = 9, Squares[8] = 64, and so
on. Then prompt the user for a number from 0 through 1000 and write pseudocode to check if
that number is a perfect square (i.e., if the user inputs X, check to see if X is a value in the
array). Use a serial search for this program.
Answer:
count = 0
arr = []
index = 0
for i in range(100):
arr.append(i*i)
n = int(input("Enter a number from 0 through 1000:\n"))
while(count == 0) and (index < 100):
if n == arr[index]:
count = 1
break
index += 1
if(n >= 0) and (n <= 1000):
if count == 1:
print("Number ",n," is a perfect square")
else:
print("Number ",n," not a perfect square")
else:
print("Number is out of range")
Pseudo Code:
Declare Count, Number, i, Index as integer
Declare Arr as array
For(i=0; i<100; i++)
Arr[i] = i*i
End For
While (Count ==0) AND (Index<100)
If Number == Arr[Index]
Count = 1
Break
End If
End While
If (Number >=0) AND (Number <= 1000)
If Count == 1
Write “Number ” + Number+ “ is a perfect square”
Else
Write “Number ” + Number+ “ is not a perfect square”
End If
Else
Write “Number is out of range”
End If