Ex9-1-1 in Algorithm -- Algorithm -- Exercise

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:

Ch9.pdf (rutgers.edu)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值