Given an integer N, the task is to find N elements which fail the below-sorting algorithm. If none of the N elements fail, then print -1.
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])
Examples:
Input: N = 10 Output: 10 9 8 7 6 5 4 3 2 1 Input: N = 2 Output: -1
Approach: On solving for various cases, we can observe that only for n<=2, the given algorithm is invalid. Any value of N above that will fail on the given algorithm. A sorted array consisiting of N numbers(1, 2, 3 . . N) in reverse order cannot be sorted using this given algorithm.
Below is the implementation of the above approach:
C++
// C++ program to find a case where the // given algorithm fails #include <bits/stdc++.h> using namespace std; // Function to print a case // where the given sorting algorithm fails void printCase( int n) { // only case where it fails if (n <= 2) { cout << -1; return ; } for ( int i = n; i >= 1; i--) cout << i << " " ; } // Driver Code int main() { int n = 3; printCase(n); return 0; } |
Java
// Java program to find a case where the // given algorithm fails import java.io.*; class GFG { // Function to print a case where // the given sorting algorithm fails static void printCase( int n) { // only case where it fails if (n <= 2 ) { System.out.print(- 1 ); return ; } for ( int i = n; i >= 1 ; i--) System.out.print(i + " " ); } // Driver Code public static void main (String[] args) { int n = 3 ; printCase(n); //This code is contributed by akt_mit } } |
Python 3
# Python 3 program to find a case # where the given algorithm fails # Function to print a case where # the given sorting algorithm fails def printCase(n): # only case where it fails if (n < = 2 ) : print ( "-1" ) return for i in range (n, 0 , - 1 ): print (i, end = " " ) # Driver Code if __name__ = = "__main__" : n = 3 printCase(n) # This code is contributed # by ChitraNayal |
C#
// C# program to find a case where the // given algorithm fails using System; class GFG { // Function to print a case where // the given sorting algorithm fails static void printCase( int n) { // only case where it fails if (n <= 2) { Console.Write(-1); return ; } for ( int i = n; i >= 1; i--) Console.Write(i + " " ); } // Driver Code public static void Main() { int n = 3; printCase(n); } } // This code is contributed // by Akanksha Rai |
PHP
<?php // PHP program to find a case where // the given algorithm fails // Function to print a case where // the given sorting algorithm fails function printCase( $n ) { // only case where it fails if ( $n <= 2) { echo (-1); return ; } for ( $i = $n ; $i >= 1; $i --) { echo ( $i ); echo ( " " ); } } // Driver Code $n = 3; printCase( $n ); // This code is contributed // by Shivi_Aggarwal ?> |
3 2 1
Time Complexity: O(N)
Auxiliary Space: O(1)