void swap(int *a, int *b) {
if(a == b) return ;
int temp = *a;
*a = *b;
*b = temp;
return ;
}
int partition1(int *a, unsigned low, unsigned high) {
if(low >= high) return 0;
int i = 0;
int pVotPos = low; //pVotPos指向根据pVotVal大小分割处的小
int pVotVal = a[low];
for(i=low+1;i<=high;i++) {
if(a[i]<pVotVal) {
pVotPos++;
swap(a+pVotPos, a+i);
}
}
swap(a+low, a+pVotPos); //把小的换到前面
return pVotPos;
}
int partition2(int *a, unsigned low, unsigned high) {
if(low >= high) return 0;
int i = 0;
int pVotPos = low+1; //pVotPos指向根据pVotVal大小分割处的大
int pVotVal = a[low];
for(i=low+1;i<=high;i++) {
if(a[i]<pVotVal) {
swap(a+pVotPos, a+i);
pVotPos++;
}
}
swap(a+low, a+pVotPos-1); //大的左边一个位置上存的即为小,把小的换到前面
return pVotPos-1;
}
int partition3(int *a, unsigned low, unsigned high) {
if(low >= high) return 0;
int i = low, j = high;
int pVotVal = a[low]; //把pVotPos的值存起来,并形成一个可用的槽
while(i<j) {
while(a[j]>pVotVal && j>i) j--; //从末端找小的
a[i]=a[j]; //换到前面去
while(a[i]<pVotVal && i<j) i++; //从前端找大的
a[j]=a[i]; //换到后面去
}
a[j]=pVotVal;
return j;
}
快排中partition函数的几种写法记录
最新推荐文章于 2024-04-30 09:00:00 发布