arrays - 快速排序中的循环条件
问题描述
考虑下面的代码进行快速排序
#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++;
}
解决方案
推荐阅读
- sql - DB2 z/OS 触发器中的非法符号 DECLARE
- javascript - 限制输入的最大允许长度元素
- python - 如何仅使用 tensorflow 操作附加 1 级张量?
- python - 将文本与关键字集(NLP)匹配的好方法是什么
- java - 在 Spring Boot 应用程序上下文中找不到 Bean
- python - 如何用元素符号分隔列表中的元素
- vuejs2 - Vue:js 计算属性在更改存储状态时未更新
- java - Java:如何检查方法是否抛出异常并在抛出异常时终止?
- python - “订单”对象不可迭代 [Django]
- .net - 将 Blazor WASM 移动到子目录(基目录静态文件)