Sorting___Searching
Sorting___Searching
BUBBLE SORT
NUMS = [15,30,85,25,40,90,50,65,20,60]
output "Before sorting"
loop C from 0 to NUMS.length -1
output NUMS[C]
end loop
Loop i = 0 to a.length - 1
Loop j = i+1 to a.length - 1
if A[i] > A[j]
// Swap the entries
Temp = A[i]
A[i] = A[j]
A[j] = Temp
end if
end loop
end loop
LINEAR SEARCH
FOUND = false
I = 0
COL={5,12,-9,0,23}
SEARCHVAL= -9
COL.resetNext()
loop while COL.hasNext() and not FOUND
if COL.getNext() == SEARCHVAL then
FOUND = true
else
I = I + 1
end if
end loop
if FOUND then
output I
else
output "Not Found"
end if
LINEAR SEARCH – PSEUDOCODE
WITH COLLECTIONS
NAMES = “Bob”,”Betty”,”Kim”,”Lucy”,”Dave”
output "These names start with D"
loop while NAMES.hasNext()
NAME = NAMES.getNext()
if firstLetter(NAME) == "D" then
output NAME
end if
end loop
BINARY SEARCH
1. Set the low index to the first element of the array and the high index to the last
element.
2. Set the middle index to the average of the low and high indices.
• If the element at the middle index is the target element, return the middle
index.
• Otherwise, based on the value of the key to be found and the value of the
middle element, decide the next search space.
• If the target is less than the element at the middle index, set the high index
to middle index – 1.
• If the target is greater than the element at the middle index, set the low
index to middle index + 1.
3. Perform step 2 repeatedly until the target element is found or the search space
is exhausted.
BINARY SEARCH
29 false 12 0 true 6 13
15 false 12 7 true 10 29
15 false 9 7 true 8 19
15 false 9 9 true 9 17
15 false 8 9 false -1