0

Help me correct the logical error

I was trying different insertion operations In the code attached below, I have a problem in the insorder function, Size of array 5 My sample input: 88 56 4 2 5 Choice is 3 Element to add : 106 Output: 106 2 4 5 56 88 In actual output we expect 106 to be added at the last position but here it gets inserted as the first position. If I choose choice 3 in the second program iteration the code works fine. I don't understand why. Please help, sorry for the long code and the inconvenience with the infinite loop. SUMMARY: the element is not getting inserted at the end of the array instead gets added in the beginning. NOTE: Since I have added an infinite loop please try the code in some other compiler. https://sololearn.com/compiler-playground/c6lIrrdd2aDJ/?ref=app

7th Nov 2024, 4:03 PM
Sanjana
Sanjana - avatar
4 Réponses
0
Note that the while loop does not work well in Sololearn's codebit input method. So testing your code here is not easy. Your ordered insert looks unnecessarily complicated. Why not insert first, sort later?
8th Nov 2024, 3:01 AM
Bob_Li
Bob_Li - avatar
0
Bob_Li the given task requires me to sort first and then insert by order
8th Nov 2024, 4:00 AM
Sanjana
Sanjana - avatar
0
try replacing your insorder with this void insorder(int *a,int *n,int e) { for(int i=0;i<(*n-1);i++) { for(int j=0;j<(*n-i-1);j++) { if (a[j]>a[j+1]) { int temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; } } } int p; if(e > a[*n]) p = *n; else{ for (int i=0;i<(*n-1);i++) { if(e >= a[i] && e < a[i+1]) p=i; } } inspos(a,n,p,e); }
8th Nov 2024, 5:49 AM
Bob_Li
Bob_Li - avatar
0
Here is your code that I modified for Sololearn. I used the insert before sort method, and factored out the print array function from inspos. This way, inspos does not need to be the last function called just because of the print array part is stuck to it. It simplifies the code because you don't have to solve for the correct position in insorder. The code could even be simpler if you're not forced to used malloc. Also, what is key in an array? An array have index and value, key is a hash table concept. https://sololearn.com/compiler-playground/cJsJXLJI8wkO/?ref=app
8th Nov 2024, 6:20 AM
Bob_Li
Bob_Li - avatar