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;
}