Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am trying to do insertion sort algorithm with given number of arrays, but my o

ID: 3715564 • Letter: I

Question

I am trying to do insertion sort algorithm with given number of arrays, but my output is repeating 1 1 3 3 5 5 6 8 8 9

how can i fix this?

my code is below

#include<iostream>
using namespace std;


int main()
{
int i,j,n,aCurrent;
int a[]={1, 3, 5, 6, 0, 4, 2, 8, 9, 7};
n= 10;

for(i=1;i<n;i++)

{
aCurrent=a[i];
int j=i-1;
for (j=0; j< i; j++)
if (a[j]>=aCurrent) break;

for (int k=i-1; k>=j;k--)
a[k+1]=a[k];

}

cout<<"The sorted arrays are: ";
for(i=0;i<n;i++)
{
cout <<a[i] <<" ";
}

return 0;
}

Explanation / Answer

ANSWER:- Modified code given below please try this code

#include<iostream>

using namespace std;

int main()

{

int i,j,n,aCurrent;

int a[]={1, 3, 5, 6, 0, 4, 2, 8, 9, 7};

n= 10;

for(i=1;i<n;i++)

{

aCurrent=a[i];

int j=i-1;

while (j >= 0 && a[j] > aCurrent)

{

a[j+1] = a[j];

j = j-1;

}

a[j+1] = aCurrent;

}

cout<<"The sorted arrays are: ";

for(i=0;i<n;i++)

{

cout <<a[i] <<" ";

}

return 0;

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote