首页 > 解决方案 > 快速排序中的循环条件

问题描述

考虑下面的代码进行快速排序

#include <stdio.h>

void printArray(int *A, int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d ", A[i]);
    }
    printf("\n");
}

int partition(int A[], int low, int high)
{
    int pivot = A[low];
    int i = low + 1;
    int j = high;
    int temp;

    do
    {   
     while (A[i] <=pivot )
       {
        i++;
       }
        while (A[j] > pivot)
        {
            j--;
        }

        if (i < j)
        {
            temp = A[i];
            A[i] = A[j];
            A[j] = temp;
        }
    } while (i < j);

    // Swap A[low] and A[j]
    temp = A[low];
    A[low] = A[j];
    A[j] = temp;
    return j;
}

void quickSort(int A[], int low, int high)
{
    int partitionIndex; // Index of pivot after partition

    if (low < high)
    {
        partitionIndex = partition(A, low, high); 
        quickSort(A, low, partitionIndex - 1);  // sort left subarray 
        quickSort(A, partitionIndex + 1, high); // sort right subarray
    }
}

int main()
{
    
    int A[] = {9, 4, 4, 8, 7, 5, 6};
    n =7;
    printArray(A, n);
    quickSort(A, 0, n - 1);
    printArray(A, n);
    return 0;
}

我对分区函数中的 do while 循环有疑问。对于数组输入的给定值,下面的循环应该已变为无限或可能导致未定义的行为,因为数组中没有大于 9 的值,我将继续增加并将超过循环应该显示的数组大小一些错误,但代码运行良好,为什么?

while (A[i] <= pivot)
        {
            i++;
        }

标签: arrayscsortingquicksort

解决方案


推荐阅读