归并排序merge sort:
void merge_sort(vector<int> &v, int x, int y)
{
vector<int> temp;
if(y-x == 1)return;
int m = x + (y - x) / 2;
merge_sort(v, x, m);
merge_sort(v, m, y);
int i = x, j =m ;
while(i < m || j < y)
{
if(i >= m || (j < y && v[i] >= v[j]))
temp.push_back(v[j++]);
else temp.push_back(v[i++]);
}
for(int i = x; i < y; i++)
v[i] = temp[i - x];
}
快速排序quick sort:
int partition(vector<int> &v, int x, int y)
{
int pivot=v[x];
int i=x+1,j=x+1;
for(;i<y;i++)
if(v[i]<pivot)
{
swap(v[i],v[j]);
j++;
}
swap(v[x], v[j-1]);
return j-1;
}
void quick_sort(vector<int> &v, int x, int y)
{
if(y-x<2) return;
int pivot = partition(v, x, y);
quick_sort(v, x, pivot);
quick_sort(v, pivot+1, y);
}
二分查找(包括递归实现和非递归实现):
int binary_search(vector<int> &v, int x, int y, int s) //递归,[x,y]是闭区间
{
if(y-x<1) return v[x] == s ? x : -1;
int mid = (x+y)/2;
if(v[mid] == s) return mid;
if(v[mid] > s) return binary_search(v, x, mid - 1, s);
return binary_search(v, mid + 1, y, s);
}
int binary_search2(vector<int> &v, int x, int y, int s) //while循环,不递归,[x,y]是闭区间
{
int mid = (x + y) / 2;
while(x<=y)
{
if(v[mid] == s) return mid;
if(v[mid] > s) y = mid-1;
else x = mid + 1; //因为mid可能等于x,如果改成x=mid会无限循环
mid = (x + y) / 2;
}
return -1;
}
lower_bound和upper_bound:
int lower_bound(vector<int> v, int x, int y, int s)
{
int mid = (x + y) / 2;
while(x<y)
{
if(v[mid] >= s) y = mid;
else x = mid+1;
mid = (x + y) / 2;
}
return x;
}
int upper_bound(vector<int> v, int x, int y, int s)
{
int mid = (x + y) / 2;
while(x < y)
{
if(v[mid] <= s) x = mid+1;
else y = mid;
mid = (x + y) / 2;
}
return x;
}