Arrays Flashcards
What is an array?
A data structure that allows you to hold many items of data which is referenced by one identifier
e.g. array usernames[10]
How do I add to an array?
array usernames[10] // 10 is the fixed number in this case
usernames[0] = “psmith”
usernames[1] = “ltorvalds”
usernames[2] = “pwatts”
usernames[3] = “sjones”
usernames[4] = “mpatel”
How do I find an array’s length?
usernames.length //this returns 10
How would you write a FOR loop to output all the usernames in the array?
for i = 0 to usernames.length
print(username[i])
endfor
What is a linear search?
Each item is examined in sequence until the item is found or the end of the list is reached
Adapt code so that the user can enter a username and find out if it is present in the array (Linear search)
search = input(“Type in username: “)
for i in range(usernames.length)
if usernames[i] == search
print(“Name found”)
What is bubble sort?
Each item in a list is compared to the one next to it, and if it is greater, they swap places.
At the end of one pass through the list, the largest item is at the end of the list
This is repeated until the items are sorted
How could you swap items using an array (Bubble sort)
names = [“Sam”, “Ron”, “Tom”, “Bob”, “Mo”]
numItems = len[names]
for i = 0 to numItems - 2
for j = 0 to numItems - i - 2
if names[j] > names[j + 1] then
temp = names[j]
names[j] = names[j+1]
names[j+1] = temp
endif
next j
next i