Sorting Arrays Bubble

General question about this code because I’m trying to fully understand what’s going on. Question at bottom…

void swap(int numbers, int i, int j) {
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}

void sort(int numbers, int size) {
for (int pass = 0; pass < size; pass++) {
for (int i = 1; i < size; i++)
if (numbers[i] < numbers[i - 1])
swap(numbers[i], numbers[i - 1]);

}

}

int main()
{
int numbers = { 7, 4, 2, 1 };
sort(numbers, size(numbers));
for (int number : numbers)
cout << number;

return 0;

}

“for (int number : numbers)”
So, my question involves this line, and I am curious why I have to loop over the numbers array to get a desired result because if I remove this line I get hexadecimal values?

Hi, this line: for (int number : numbers) is used to print each individual element of the array in its sorted order. If we don’t iterate through the array and access its elements individually, but instead try to print the numbers array directly, we will get a hexadecimal value. This is because printing the array name directly outputs the memory address of the array, not the actual elements. An array in C++ is represented as a pointer to the first element of the array in memory, hence the memory address is shown

1 Like

Oooooh okay cool this makes much more sense now! Thank you!