I finally had the time to finish this homework as well.
LinearSearch(x,items) searches the items for the given item x . The algorithm starts at the first position in items and iterates over each item while comparing with x. If the one item equals the item x, the algorithm the position of this item, otherwise -1.
- Init index variable to zero(0)
- Iterate over items and compare the i-th element of items with x
- increase the index variable by one and start over with 2
- if the i-th item and x are equal return the i otherwise -1
Heapsort(items) is a function to sort a collection of items by using a tree datastructure. The passed items are transformed in a tree-based datastructure with a defined order. Each tree-node is either smaller or equal to his parent node. Next we create a sorted region by removing the largest element in the tree(the root) and inserting this into a array. By repeating this step the sorted array is created and henceforth the tree is shrinked.
- create a binary tree from the given array
- iterate over the tree and move the root of the tree to a array, the sorted array
- update the remaining tree to create a new tree with the root as the largest element
- by repeating step you create a sorted array
- as soon as the heap is empty we are finished
SelectionSort(items) is a in-place sort algorithm, which means the items are not moved to different arrays or other structures. It finds the smallest element in the items collection and swaps it with a specified different element.
- finding the smallest element in the array
- find minimum from start to end
- swap the found element with the first element
- find the next smallest element in the array
- not all elements has to be concerned because the smallest element is on position 0 already so we can start from 1
- swap the second smallest element with the second element
- repeat step 3 and 4 until we are at the end of the list
In terms of costs this algorithm has a runtime of O(n*n) which makes it inefficient for large lists.