I am having trouble ascending and descending an array with an insertion code. I
ID: 3624945 • Letter: I
Question
I am having trouble ascending and descending an array with an insertion code. I know the while loop displays it in ascending order but i cannot get it to display from the original, ascending or descending. It just keeps repeating the first element in the array. Any help will be appreciated. The first code is the original and the other code is my attempt at the problem.const int len = 5;
int i,j;
int elem; // Temporary hold for each element.
int A[len] = {9, 1, 3, 6, 5};
// Pick out each element in turn.
for (j=1; j<len; j++)
{
elem = A[j];
i=j-1;
// Look for a place to insert it.
while (i>=0 && A[i] > elem)
{
A[i+1]=A[i];
i--;
}
A[i+1]=elem; // Insert it.
}
// My attempt at the code
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int len = 5;
int i,j;
int elem; // Temporary hold for each element.
int A[len] = {9, 1, 3, 6, 5};
cout << "BEFORE SORT: ";
for (j=1; j<len; j++)
{
elem = A[j];
i=j-1; //
cout << A[i] <<end1;
while (i>=0 && A[i] > elem)
{
A[i+1]=A[i];
i--;
}
A[i+1]=elem; //
}
system("pause");
return 0;
}
Explanation / Answer
// now working erfectly with intermediate steps.....
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const int len = 5;
static int p=1;
int i,j;
int elem; // Temporary hold for each element.
int A[len] = {9, 1, 3, 6, 5};
cout << "BEFORE SORT: ";
for (j=0; j<len; j++)
cout << A[j] <<" ";
cout<<endl;
for (j=1; j<len; j++)
{
elem = A[j];
i=j-1; //
while (A[i] > elem && i>=0 )
{
A[i+1]=A[i];
i=i-1;
}
A[i+1]=elem;
cout << "step " << (p++) << ":";
for (int k=0; k<len; k++)
cout << A[k] <<" ";
cout<<endl;
}
cout << "AFTER SORT: ";
for (j=0; j<len; j++)
cout << A[j] <<" ";
cout<<endl;
system("pause");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.