0
Insertion Sort and Average
I'm supposed to: 1..Code a regular c-type function that takes in an array and performs an insertion sort. 2. Find the average number of insertions it takes to sort a 10-element random integer array. Answer: 6.98 insertions avg When I run the program, the number of swaps is 9000 and my average is 9. What is it I'm doing wrong? https://code.sololearn.com/cOKaYf6m04qM
2 Respuestas
+ 3
On line 45 you arent swapping, you are just copying the value over. Also you should count the insertions only and not every iteration of the outer loop (that'll always be 9 per run), so line 42 onwards should look maybe something like
bool swapped = false;
while(...){
int tmp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = tmp;
swapped = true;
j = j - 1;
}
if(swapped) counter++;
I hope that helps.
Also, whenever you write a program, make a way to print what's going on to get feedback! That really helps too.
void printArray(int[] arr, const int n){
for(int i = 0; i++; i < n)
cout << arr[i] << " ";
cout << endl;
}
0
Thank you for the help. I fixed it up and made it a bit more neat with the print and also setprecision.