【发布时间】:2018-10-29 21:25:20
【问题描述】:
我有以下代码:
// C program for implementation of Bubble sort
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("n");
}
// Driver program to test above functions
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}
唯一让我感到困惑的部分是第一个 for 循环中的 i < n-1 和 BubbleSort 函数内部 for 循环中的 J< n-i-1。为什么它们都没有设置为i <= n-1 和J<=n-i-1?例如,第一次迭代总共 n = 7,因此这意味着它应该在外循环中循环 6 次,在内循环中循环 6 次。但是,如果没有 <= 符号,每个循环只会进行 5 次迭代。在网站上,它说明了两个循环都经历了 6 次迭代,但是我不确定如果没有 <=in 会发生这种情况。
【问题讨论】:
-
具有 N 个条目的 C 数组的索引为 0 到 N-1。
标签: c bubble-sort