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

Hi! I have having a little trouble with Insertion. Question: Write a program to

ID: 671893 • Letter: H

Question

Hi! I have having a little trouble with Insertion.

Question:

Write a program to sort a list of integers using Insertion-Sort.

To perform the sort once you enter the integers (about 50) to an array (for example A[ ]), the call the function Insertion-Sort (int B[ ], int n) where B is the array to be sorted and n is the number of integers of the array.

Based on a skeleton code the professor sent us.

int main ( )

{ int * A;

Int n;

cout << endl << “enter number of elements of the array”;

cin >> n;

int A=new int [n];

// Enter n integers into the array using cin and a for-loop

Insertion-Sort (A, n); // call Insertion-Sort

cout << endl << “ The list sorted is : “;

// sort the list using a for-loop

return (0);

}

void Insertion-Sort (int B[], int n)

{ //write subroutine

}

Thanks in advance!

Explanation / Answer

#include <iostream>

using namespace std;
void InsertionSort (int B[], int n)
{
int temp, i, j;

for (i = 1;i < n;i++)
{
temp = B[i];
j = i - 1;
while (temp < B[j] && j >= 0)
{
B[j + 1] = B[j];
j = j - 1;
}
B[j + 1] = temp;
}
}
int main ( )
{ int * A;
int n;
cout << endl << "enter number of elements of the array: ";
cin >> n;
A=new int[n];
for(int i=0;i<n;i++){
cout<<(i+1)<<" element= ";
cin>>A[i];
}
InsertionSort(A, n); // call Insertion-Sort
cout << endl << "The list sorted is : "<< endl;
for(int i=0;i<n;i++){
cout<<(i+1)<<" element: "<<A[i]<<endl;
}
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