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< n-i-1
in the inner for loop inside the BubbleSort function. Why arent they both set to i <= n-1
and J<=n-i-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. But, without the <=
sign it would only be 5 iterations per loop. 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.
Note the use of arr[j+1]
. Let's say your array has n = 7
. Then when i = 0
and j = n - i - 1 = 6
, you would be accessing 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.
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.