0

I am new in cpp language. I trying solve a problem on Insertion sort. However, presentation error happened while submit to online judge. in program I have to show intermediate sequence in a line for each step of Insertion sort. Here is my code so far:

void InsertionSort(int *arr, int n)
{

for (int i = 1; i < n; i++)
{
    int key = arr[i];
    int j = i - 1;
    while (j >= 0 && arr[j] > key)
    {

        arr[j + 1] = arr[j];
        j--;
    }

    arr[j + 1] = key;
    for (int k = 0; k < n; k++)
        cout << arr[k] << " ";
    cout << endl;
}}

Output:

1 2 3<Here is space.want to remove it> 
1 2 3<Here is space.want to remove it>

Thank you in advance.

Mrsk
  • 129
  • 5
  • 13
  • Instead of for each element doing `cout << arr[k] << " ";`, do that for each element except for the last one. Then, output the last one with a newline. – Fureeish Mar 03 '19 at 15:18
  • @Fureeish would you plz show/explain me how? – Mrsk Mar 03 '19 at 15:47

1 Answers1

1

Don't std::cout << arr[k] << ' ' all n elements. Apply that to every single one except for the last one. Then, output that element, but instead of having it followed by a space, have it followed by '\n' or std::endl, preferably the former one:

for (int k = 0; k < n - 1; k++)
    cout << arr[k] << " ";
cout << arr[n - 1] << '\n';

Notice the n - 1 instead of n in the for() loop condition. This will apply the body for all the element except for the last one.

Then, we need to treat the last element (represented by the n - 1th index) differently - we don't want to print it followed by a " ", but rathar a newline. That's why we do << '\n';. Note that std::endl would work too, but it's unnecessary. I encourage you to read about std::endl vs '\n'.

Fureeish
  • 12,533
  • 4
  • 32
  • 62