[英]C++ - Implementing quicksort using unsigned integers only?
我有
std::vector<unsigned int> numbers;
多数民众赞成在填充数字,并需要不使用int索引而被快速排序-仅允许将无符号int用作向量索引。
在某些情况下,由于索引将所有“ int”转换为“ unsigned int”时,我见过的所有quickSort示例均会中断(由于j--)。
编辑:这是一个例子
void quickSort(std::vector<unsigned int> &numbers, unsigned int left, unsigned int right) {
unsigned int i = left, j = right;
unsigned int tmp;
unsigned int pivot = numbers.size()/2;
/* partition */
while (i <= j) {
while (numbers[i] < pivot)
i++;
while (numbers[j] > pivot)
j--;
if (i <= j) {
tmp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = tmp;
i++;
j--;
}
};
/* recursion */
if (left < j)
quickSort(numbers, left, j);
if (i < right)
quickSort(numbers, i, right);
}
修改后的版本: http : //diogopinho.hubpages.com/hub/easy-quicksort-with-examples
Segfaults上面的示例,因为如果j为unsigned int并变为0,则j--成为一个巨大的数字(0xffffffff),而(i <= j)始终为true。 有谁知道如何仅使用unsigned int索引来实现quickSort?
如果您查看链接到的页面,其中包含枢轴的描述,则说明该页面的实现不正确。 这可能导致找不到枢轴,并且j变得小于0。如果将枢轴正确选择为包含在范围内的数字,则我认为该算法也适用于无符号整数。
这篇文章很老,但是如果仍然有人需要,他可以在这里找到可以容忍unsigned int索引的实现。
int partition(int *a,int start,int end)
{
int pivot=a[end];
//P-index indicates the pivot value index
int P_index=start;
int i,t; //t is temporary variable
//Here we will check if array value is
//less than pivot
//then we will place it at left side
//by swapping
for(i=start;i<end;i++)
{
if(a[i]<=pivot)
{
t=a[i];
a[i]=a[P_index];
a[P_index]=t;
P_index++;
}
}
//Now exchanging value of
//pivot and P-index
t=a[end];
a[end]=a[P_index];
a[P_index]=t;
//at last returning the pivot value index
return P_index;
}
void Quicksort(int *a,int start,int end)
{
if(start<end)
{
int P_index=partition(a,start,end);
Quicksort(a,start,P_index-1);
Quicksort(a,P_index+1,end);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.