A couple of things:
int i,j,tmp;
can be formatted better:
int i, j, tmp;
and actually isn't even necessary, as is explained later.
int j; for (j = 0; j < size; j++) { std::cout << array[j] << std::endl; }
C++ conventions have braces on the same line as the statement:
int j;
for (j = 0; j < size; j++) {
std::cout << array[j] << std::endl;
}
In fact, the first line can be merged into the loop:
for (int j = 0; j < size; j++) {
std::cout << array[j] << std::endl;
}
j = i; while (j > 0 && arr[j - 1] > arr[j]) { tmp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = tmp; j--; }
can be a for loop, as explained:
j = i; // Initialization
while (j > 0 && arr[j - 1] > arr[j]) { // Condition
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--; // Decrement
}
which turns into:
for (j = i; j > 0 && arr[j - 1] > arr[j]; j--) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
}
Now, why is the first line not necessary, and even discouraged?
Well, because you should declare variable right where you need them, and not before:
void insertion_sort(int arr[], int length)
{
for (int i = 1; i < length; i++) {
for (int j = i; j > 0 && arr[j - 1] > arr[j]; j--) {
int tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
}
}
}