Your task is to sort an array of integer numbers by the product of the value and the index of the positions.
For sorting the index starts at 1, NOT at 0! The sorting has to be ascending. The array will never be null and will always contain numbers.
My solution
int* sortByValueAndIndex(int* array, int arrayLength) {
int* extraArray = malloc(arrayLength * sizeof(int));
for (int index = 0; index < arrayLength; index++) {
extraArray[index] = array[index] * (index + 1);
}
/* Bubble sort */
for (int firstIndex = 0; firstIndex < arrayLength - 1; firstIndex++) {
for (int secondIndex = 0; secondIndex < arrayLength - firstIndex - 1; secondIndex++) {
if (extraArray[secondIndex] > extraArray[secondIndex + 1]) {
int tmp = array[secondIndex];
array[secondIndex] = array[secondIndex + 1];
array[secondIndex + 1] = tmp;
tmp = extraArray[secondIndex];
extraArray[secondIndex] = extraArray[secondIndex + 1];
extraArray[secondIndex + 1] = tmp;
}
}
}
free(extraArray);
return array;
}