简体   繁体   English

气泡排序逻辑,迭代次数

[英]Bubble sort logic, number of iterations

I have the following code: 我有以下代码:

// 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; 
} 

The only part that makes me confused is where i < n-1 in the first for loop and J< ni-1 in the inner for loop inside the BubbleSort function. 令我感到困惑的唯一部分是,BubbleSort函数内部的第一个for循环中的i < n-1和内部的for循环中的J< ni-1 Why arent they both set to i <= n-1 and J<=ni-1 ? 为什么它们都设置为i <= n-1J<=ni-1 For instance, the first iteration would be a total of n= 7, therefore it means it should go through the loop for 6 times in the outer loop and 6 times in the inner for loop. 例如,第一次迭代的总数为n = 7,因此这意味着它应该在外循环中循环6次,在内循环中循环6次。 But, without the <= sign it would only be 5 iterations per loop. 但是,如果没有<=号,则每个循环仅进行5次迭代。 On the website, it has illustrated that both loops do go through 6 iterations however Im not sure how would that happen without the <= in place. 在网站上,它已经说明了两个循环都经过了6次迭代,但是我不确定如果没有<=话该怎么办。

Source: https://www.geeksforgeeks.org/bubble-sort/ 资料来源: https : //www.geeksforgeeks.org/bubble-sort/

Note the use of arr[j+1] . 注意使用arr[j+1] Let's say your array has n = 7 . 假设您的数组有n = 7 Then when i = 0 and j = n - i - 1 = 6 , you would be accessing arr[j+1] = arr[6 + 1] = arr[7] . 然后,当i = 0j = n - i - 1 = 6 ,您将访问arr[j+1] = arr[6 + 1] = arr[7] However, arr only had 7 elements to begin with, so index 7 is out of bounds since the indices begin at 0 , with arr[6] being the seventh element. 但是, arr只有7个元素开头,因此索引7超出范围,因为索引从0开始,而arr[6]是第七个元素。

As for why it doesn't matter, the final element of the array is already swapped when comparing it to the next-to-last element. 至于为什么没关系,将数组的最后一个元素与倒数第二个元素进行比较时已经交换了。 Or if the array only had 1 element, it is already sorted. 或者,如果数组只有1个元素,则它已经排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM