I'm trying to practice programming by implementing different algorithms in different languages. I have two questions about a c++ implementation for insertion sort. First, why do most implementations in c++ include a length parameter, while others, such as java, just access the arrays length in the for loop? The next question is why do most implementations swap the variable inside the while loop, instead of just swapping at the very end? I have included two implementations to make it easier to talk about.
Java implementation:
void insertionSort(int[] arr) {
int i, j, newValue;
for (i = 1; i < arr.length; i++) {
newValue = arr[i];
j = i;
while (j > 0 && arr[j - 1] > newValue) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = newValue;
}
}
C++ Implementation:
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}
It seems like the c++ implementation will perform worse because of the swapping in the while loop. Specifically, is there a reason why c++ doesn't access array sizes directly and also is it necessary to implement the while loop like that, or is it just sloppy programming? Thank you in advance.