The following algorithm determines if an array of numbers is sorted:
// Input: A[0, ..., n-1]
// Output: true or false depending on whether the array is sorted
// Variables used: i -- loop index
for i = 2, ..., n-1:
if A[i-1] > A[i]:
return false
return true
The following algorithm determines the number of ones in the binary representation of a number \(n\):
ALGORITHM ones(n)
// Input: n --- a nonnegative integer
// Output: The number of ones in the binary representation of n
if n <= 1:
return n // n is 0 or 1
else:
lastDigit = n mod 2 // lastDigit=1 if n is odd, lastDigit = 0 if n is odd
otherDigits = ones(n / 2) // integer division here
return lastDigit + otherDigits