二分实现
来源:互联网 发布:区间删失数据 编辑:程序博客网 时间:2024/05/01 11:22
In Quicksort algorithm implementation, the partition method is the key to make average performance as O(nlgn). As written in different algorithm textbook, it has different implementations, in many domestic data structure textbook, the 2 pointers move towards each other, accoring to this implementation, it is very hard to deal with duplicated element condition. However, in Leiserson's Introduction to Algorithm, the 2 pointers move in same direction, its performance is really enhanced and the duplicated elements can be handled gracefully as well。
Method 1: choose the last element in array as pivot,the swap loop starts from the first element of array
template<class T>
int partition1(T A[], int p, int q) {
T pivot = A[q];
int i = p-1;
for (int j = p; j < q; j++) {
if (A[j] <= pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i+1], A[q]);
return i+1;
}
Method 2:choose the first element as pivot, swap loop starts from second element of array
template<class T>
int partition2(T A[], int p, int q) {
T pivot = A[p];
int i = p;
for (int j=p+1; j<=q; j++) {
if (A[j]<=pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i], A[p]);
return i;
}
Method 1: choose the last element in array as pivot,the swap loop starts from the first element of array
template<class T>
int partition1(T A[], int p, int q) {
T pivot = A[q];
int i = p-1;
for (int j = p; j < q; j++) {
if (A[j] <= pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i+1], A[q]);
return i+1;
}
Method 2:choose the first element as pivot, swap loop starts from second element of array
template<class T>
int partition2(T A[], int p, int q) {
T pivot = A[p];
int i = p;
for (int j=p+1; j<=q; j++) {
if (A[j]<=pivot) {
i++;
std::swap(A[i], A[j]);
}
}
std::swap(A[i], A[p]);
return i;
}
0 0
- 二分实现
- Java实现 二分查找
- 二分查找递归实现
- 正确实现二分查找
- Python实现二分查找
- 二分查找实现
- 二分查找实现
- 二分查找实现
- Java实现二分查找
- 二分查找实现
- java实现二分查找
- java实现二分查找
- 二分查找的实现
- Java二分查找实现
- 二分实现插排
- c++实现二分查找
- 二分查找(实现)
- java 实现二分查找
- 在windows里写NMake makefile,编译时遇到的cl.exe command line : error D8003 missing source filename(缺少源文件名)
- Maven-5:Maven仓库:本地仓库 vs. 远程仓库
- hdu 悼念512汶川大地震遇难同胞——选拔志愿者
- Oracle内存管理(之二)
- 怎么干翻大众点评
- 二分实现
- Nexus 教程
- int const *p \ const int *p \ const int * const p 解析
- 批量更改文件后缀
- UITabbar 中的 item的字体颜色 item点击后的tint颜色 和图片颜色的修改
- 树状数组的大概理解
- Java实现双链表
- C++ Primer Plus学习笔记:第二章
- pku 1845