在算法中沉迷----------------------------
在解决实际问题,总会有这样的感觉:明明算法思想已经有了,但是实现的时候却又感觉困难重重,让人复又怀疑算法的正确性,有时很不幸地陷入了这样的矛盾中。 编程不是那么简单的事情,需要编写大量的程序,和不断的总结思路,才会有进步。
好吧,废话说到这里,马上进入正题,代码上见
//向屏幕 输入 一组数,输出 这组数的最小k个数
#include <iostream>
#include <vector>
using namespace std;
//print the content of the vector
template<typename T>
void print_vector(vector<T> object)
{
vector<T>::iterator i;
for(i=object.begin(); i!=object.end(); i++)//vector is continuely stored in memory
{
cout<<*i<<'\t';
}
}
void exchange(int &a, int &b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
}
//直接将快排中的函数拿过来,函数返回pivot的下标
int partition(vector<int> &a, int start, int end)
{
//i始终指向比pivot小的数
int i = start -1;
//j指向每次要与pivot小的数
for (int j=start; j<=end-1; j++) //原来的写法:for (int j=1; j<=end-1; j++),
//在pivot左边时没有问题,但是到pivot右边时就开始有了致命伤
{
if(a[j]<=a[end]) //if(a[j]>=a[end]):对应非增序的排法; if(a[j]<=a[end]):对应非减序的排法;
{
++i;
exchange(a[i], a[j]);
}
}
exchange(a[i+1], a[end]);
return i+1;
}
//和《剑指OFFER》上的解法,不谋而合,英雄所见略同,哈哈哈
void little_kth(vector<int> &a, int k)
{
int pivot = partition(a, 0, a.size()-1);
//set the border for looking for!!!!!!!!!!!!!!!非常好的创意,夸的是自己,哈哈哈,其实源自与自己曾经看到的二分法,在文章末尾
//列出二分法代码
int start = 0;
int border = a.size()-1;
while(pivot != k && pivot !=k-1)
{
if(pivot < k-1)
{
start = pivot + 1;
pivot = partition(a,start,border); //这里的边界有问题
}
else if( pivot > k-1 )
{
border = pivot - 1;
pivot = partition(a,start,border);
}
}
}
void main()
{
//complish the action of input some numbers into the vector(between the numbers are space, end of the input is eof--enter)
vector<int> object;
int a = 0;
cout<<"input some ints,boy:"<<endl;
//actually I do not konw neither
while(cin>>a)
{
object.push_back(a);
}
//print the content of the vector
print_vector(object, object.end() );
cout<<endl;
little_kth(object, 4);
}
//二分法代码,为了找到符合条件的数组元素的下标,采用的方法,都是限定一个上下界,通过不对判断条件,缩小范围直到符合条件
//在数组a中找值为x的元素,若找到返回FOUND;没有找到,返回NOT_FOUND.
int binarySearch(const vector<int> &a, const int &x)
{
int low = 0;
int high = a.size() - 1;
while(low <= high)
{
int mid = (low + high)/2;
if(x > a[mid])
low = mid + 1;
else if(x < a[mid])
high = mid - 1;
else
return FOUND;
}
return NOT_FOUND;
}