簡體   English   中英

C ++-僅使用無符號整數實現quicksort?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM