Source
From textbook shown in Github.
Q
Show that 2th smallest of n elements can be found with
n+⌈lg n⌉-2 comparisons in worst case.
Hint:
Also find the 1th smallest element.
Solution
Solution 1
Code
C++
My own C++ code with Dev-C++
#include <iostream>
#include <cstdlib>
using namespace std;
template<class T>
class Pair
{
public:
T smallest1; // first smallest
T smallest2; // second smallest
public:
void Display()
{
cout<<"The 1th smallest element: "<< this->smallest1<<endl;
cout<<"The 2th smallest element: "<< this->smallest2<<endl;
}
};
template<typename T>
class Element
{
public:
static
Pair<T> Find2thSmallestElement_1(T *array)
{
Pair<T> current;
Pair<T> best;
Pair<T> temp;
int i;
int size;
current.smallest1 = array[0];
current.smallest2 = array[0];
best.smallest1 = array[0];
best.smallest2 = array[0];
size = sizeof(array)/sizeof(array[0]);
for(i=1;i<size;i++)
{
current.smallest1 = array[i];
if(current.smallest1 < best.smallest1 )
{
temp.smallest1 = best.smallest1;
best.smallest1 = current.smallest1;
best.smallest2 = temp.smallest1;
}else if(current.smallest1 < best.smallest2 )
{
best.smallest2 = current.smallest1;
}
}
return best;
}
};
int main()
{
int *array = new int [10] {1,2,3,4,5,6,7,8,9,10};
Pair<int> *resultPair=new Pair<int>();
cout<<"Before:"<<endl;
resultPair->Display();
// *resultPair = Element<int>.Find2thSmallestElement_1(array);
*resultPair = Element<int>::Find2thSmallestElement_1(array);
cout<<"After:"<<endl;
resultPair->Display();
}
Analysis
Comparison
Suppose there are n elements in the array A.
Worst case:
2 * n
It happens iff A is an increasing array. In this case, since the condition
current.smallest1 < best.smallest1
in if(current.smallest1 < best.smallest1 ) is always false, the condition will always be executed.
current.smallest1 < best.smallest2
in if(current.smallest1 < best.smallest2 )
Best case:
n
It happens iff A is an increasing array. In this case, only the condition will be executed.
current.smallest1 < best.smallest1
in if(current.smallest1 < best.smallest1 )
Time Complexity
O(n)
Meet Requirement of Q
No.
Sometimes, it does NOT meet requirements.
Solution 2
From the website: