快速排序是Seg Faulting

时间:2014-11-20 05:10:31

标签: c++ segmentation-fault quicksort

有人可以给我一些指示,为什么这是分段错误?我从计算机科学书中实现了这一点,而且我在调试递归时表现不佳。我只是不知道从哪里开始调试。

template<class ItemType>
void sortFirstMiddleLast(ItemType arr, unsigned int first, unsigned int mid, unsigned int last)
{
    if (arr[first] > arr[mid]) { swap(arr[first], arr[mid]); }
    if (arr[mid] > arr[last]) { swap(arr[mid], arr[last]); }
    if (arr[first] > arr[mid]) { swap(arr[first], arr[mid]); }
}

template<class ItemType>
int partition(ItemType* arr, unsigned int first, unsigned int last)
{
    unsigned int mid = first + (last - first) / 2;
    sortFirstMiddleLast(arr, first, mid, last);
    swap(arr[mid], arr[last - 1]);
    unsigned int pivotIndex = last - 1;
    ItemType pivot = arr[pivotIndex];

    unsigned int indexFromLeft = first + 1;
    unsigned int indexFromRight = last - 2;
    cout << indexFromLeft << endl;
    cout << indexFromRight << endl;

    bool sorted = false;

    while (!sorted)
    {
        while (arr[indexFromLeft] < pivot) { indexFromLeft += 1; }
        while (arr[indexFromRight] > pivot) { indexFromRight -= 1; }

        if (indexFromLeft < indexFromRight)
        {
            swap(arr[indexFromLeft], arr[indexFromRight]);
            indexFromLeft += 1;
            indexFromRight -= 1;
        }
        else { sorted = true; }
    }

    swap(arr[pivotIndex], arr[indexFromLeft]);
    pivotIndex = indexFromLeft;

    return pivotIndex;
}

template<class ItemType>
void quickSort(ItemType* arr, unsigned int first, unsigned int last)
{
    // Create the partition: S1 | pivotIndex | S2
    int pivotIndex = partition(arr, first, last);

    // Sort subarrays S1 and S2
    quickSort(arr, first, pivotIndex - 1);
    quickSort(arr, pivotIndex + 1, last);
} // end quickSort

int main()
{
    string* a = new string[27];
    a[0] = "B";
    a[1] = "Z";
    a[2] = "Y";
    a[3] = "X";
    a[4] = "W";
    a[5] = "V";
    a[6] = "U";
    a[7] = "T";
    a[8] = "S";
    a[9] = "R";
    a[10] = "Q";
    a[11] = "P";
    a[12] = "O";
    a[13] = "N";
    a[14] = "M";
    a[15] = "L";
    a[16] = "K";
    a[17] = "J";
    a[18] = "I";
    a[19] = "H";
    a[20] = "G";
    a[21] = "F";
    a[22] = "E";
    a[23] = "D";
    a[24] = "C";
    a[25] = "B";
    a[26] = "A";
    quickSort(a, 0, 26);
    for (int i = 0; i < 26; i++)
        cout << a[i] << " ";
    cout << endl;

    return 0;
};

1 个答案:

答案 0 :(得分:0)

您的递归中没有基本案例。如果您的代码在执行实际工作时没有崩溃,至少它会陷入无限递归。

递归的原理是你逐渐将你的问题减少到较小的问题,直到你得到一个无需递归就可以解决的微不足道的问题:基本情况。在您的情况下,当您要排序的子数组的长度小于或等于3.在这种情况下,您可以通过调用&#34; sortFirstMiddleLast&#34;来简单地对子数组进行排序。功能

特别是,您的分段错误来自&#34; indexFromRight = last - 2&#34;变得消极,引发下流。这是因为当要排序的子数组变小时,你的逻辑不再有效。但是,如前所述:不需要它可以工作,只需实现那些没有分区和递归的琐碎案例。