Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Algorithm
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)
Example
The code to show the implementation of our solution
#include <iostream>
using namespace std;
void invalidCase(int n) {
if (n <= 2) {
cout << -1;
return;
}
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";
invalidCase(n);
return 0;
}
Output
The case in which the algorithm goes invalid for 6 element array is −
6 5 4 3 2 1
Advertisements