Print a case where the given sorting algorithm fails in C++

In this problem, we are given a sorting algorithm and a number n. Our task is to print an array of n elements that could not be sorted by the algorithm. i.e the algorithm will fail.


loop i from 1 to n-1
   loop j from i to n-1
   if a[j]>a[i+1]
      swap(a[i], a[j+1])

Let’s look into this sorting algorithm, it is using two nested loops. The outer one will start from 1 to n-1 and inner one from i to n-1, and will check the value of inner loop element and outer loop elements at each iteration and swap out of order elements.

So this algorithm will fail for a case where the elements are sorted in reverse order. Also, we can find a solution only when n<=2.

So, for n = 5.
Output : 5 4 3 2 1
Time complexity − O(N)


The code to show the implementation of our solution

 Live Demo

#include <iostream>
using namespace std;
void invalidCase(int n) {
   if (n <= 2) {
      cout << -1;
   for (int i = n; i >= 1; i--)
      cout<<i<<" ";
int main() {
   int n = 6;
   cout<<"The case in which the algorithm goes invalid for "<<n<<" element array is :\n";
   return 0;


The case in which the algorithm goes invalid for 6 element array is −

6 5 4 3 2 1