So here is a HW problem I have been working. On I was wondering if anybody could give me a hint of what I am doing wrong. I don't want to be given the answer just hints and advice on how to solve it.
I am given this simple algorithm that finds the greatest value and the second greatest value in a array.
If A[1] < A[2],
largest = A[2], Second = A[1]
else
largest = A[1], Second = A[2];
For i in range 3 to n {
If A[i] > largest {
second = largest;
largest = A[i];
}
else
if A[i] > second
second = A[i]
}
My first task was to find the number of comparisons it makes not in big-oh terms. So I said 2n-3 because it has one in the beginning and worst case the largest element is in the first two elements of the array A so from index 3 to n it has two comparisons. So 1 + 2(n-2) = 2n - 3 comparisons.
My second task was to develop an algorithm that would use less comparisons. So I broke it down with divide and conquer and said this.
// start is the first index inclusive
// finish is the last index inclusive
// A is an array of elements
function getGreatestAndSecondGreatestValue(A, start, finish) {
T[] // T is an array of size 2
if(finish - start == 1) {
if(A[start] > A[finish]) {
T[0] = A[start]
T[1] = A[finish]
} else {
T[0] = A[finish]
T[1] = A[start]
}
return T
}
Array1 = getGreatestAndSecondGreatestValue(A,start, start + floor((last-first)/2))
Array2 = getGreatestAndSecondGreatestValue(A, start + ceil((last-first)/2), finish)
return merge(Array1, Array2);
// The greast value will be in the 0th index of the array returned and the second
// greatest value will be in the 1 index of the array.
}
// this merges two arrays keeping the greatest value on the left side of the new array and
// keeping the second greatest value on the right side of the array
function merge(Array1, Array2) {
MergedArray[] // array that will hold the merged results
if(Array1[0] > Array2[0]) {
MergedArray[0] = Array1[0]
MergedArray[1] = max(Array[1], Array2[0])
} else {
MergedArray[0] = Array2[0]
MergedArray[1] = max(Array1[0], Array2[1])
}
return MergedArray
}
For example this say we had the array
[1,4,5,2,7,9,10,19]
then is divides it
[1, 4, 5, 2] [7, 9, 10, 19]
then when it reaches a length 2 is places the highest value in index 0 for arrays the size 2
[4, 1] [5, 2] [9, 7] [19, 10]
I would then proceed to merge these
[5, 4] [19, 10]
[19, 10]
Then the greatest value is 19 and the second greatest was 10.
I then proceeded to find the number of comparisons with recurrences.
T(n) = 2T(n) + 2
There are n leaf nodes because $ 2^{log_{2}(n)} = n $ where $ log_{2}(n) $ is the height of the tree. There are then n - 1 internal nodes so n + n - 1 is 2n - 1. 2 is added to every node so then it would be 4n - 2.
For some reason after using a divide and conquer algorithm I am getting a higher number of comparisons and I am not sure why. Could somebody give me some advice on why this didn't work?