我有以下代码:
// 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;
}
唯一让我感到困惑的是,在BubbleSort函数中,第一个for循环中的i < n-1
和内部for循环中的J< n-i-1
在哪里。为什么不同时设置为i <= n-1
和J<=n-i-1
?例如,第一次迭代总共是n= 7,因此这意味着它应该在外部循环中遍历6次,在内部循环中遍历6次。但是,如果没有<=
符号,每个循环将只有5次迭代。在网站上,它已经说明了这两个循环确实经历了6次迭代,但是我不确定如果没有<=
的话会发生什么。
https://stackoverflow.com/questions/53054063
复制相似问题