Algorithms Activity 1
CSC301: Data Structures and Algorithms
Algorithm1: Complete the algorithm below that searches for a value in an array.
Algorithm Search (aValue, Array[N]]
Input: value to search for and an array of N elements
Output: True if value exists in the array; False Otherwise
Begin
Found = ……………………………………
i = ……………………………………
While (i<N AND ……………………………………) {
If (aValue == Array[i])
Found = ……………………………………
……………………………………
}
Return ……………………………………
End
Algorithm2: Complete the algorithm below that sorts an array in ascending order.
Algorithm Sort (Array[N]]
Input: An array of N elements
Output: Elements of the array are sorted in ascending order.
Begin
For i = 0 to …………………………………… {
currentMin = Array[……………………………………];
currentMinIndex = i;
For j = …………………………………… to N { // Find next minimum
If (Array[j] < ……………………………………) {
currentMin = list[j];
currentMinIndex = ……………………………………;
}
}
If (currentMinIndex != ……………………………) { // Swap if necessary;
Array[currentMinIndex] = Array [i];
Array [i] = ……………………………………;
}
}
End
CSC301-Data Structures and Algorithms
Algorithm3: Complete the algorithm below that returns the sum of the elements of an array.
Algorithm Sum (Array[N]]
Input: An array of N elements
Output: Sum of all elements of the array.
Begin
Total = ……………………………………
For i = 0 to ……………………………………
Total = Total + ……………………………………
Return Total
End
Algorithm4: Complete the algorithm below that displays the value of an array starting from the end.
Algorithm ReverseDisplay (Array[N]]
Input: An array of N elements
Output: All elements of the array are displayed starting from the end.
Begin
For i = …………………………………… to 0 Step ……………………………………
Display Array[i];
End
Algorithm5: Complete the algorithm below that checks if an array is symmetric. For example,
[4,3,2,1,2,3,4] is a symmetric array, while [4, 1, 3, 2, 4] is not.
Algorithm Symmetric (Array[N]]
Input: An array of N elements
Output: True if all elements of the right half of the array are
reversely identical to those of the left half; False; Otherwise.
Begin
For i 0 to …………………………………… {
If (Array[i] <> Array[……………………………………])
Return ……………………………………
Return ……………………………………
End
CSC301-Data Structures and Algorithms 2