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 consisting 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++
#include <bits/stdc++.h>
using namespace std;
void printCase( int n)
{
if (n <= 2) {
cout << -1;
return ;
}
for ( int i = n; i >= 1; i--)
cout << i << " " ;
}
int main()
{
int n = 3;
printCase(n);
return 0;
}
|
Java
import java.io.*;
class GFG {
static void printCase( int n)
{
if (n <= 2 ) {
System.out.print(- 1 );
return ;
}
for ( int i = n; i >= 1 ; i--)
System.out.print(i + " " );
}
public static void main (String[] args) {
int n = 3 ;
printCase(n);
}
}
|
Python 3
def printCase(n):
if (n < = 2 ) :
print ( "-1" )
return
for i in range (n, 0 , - 1 ):
print (i, end = " " )
if __name__ = = "__main__" :
n = 3
printCase(n)
|
C#
using System;
class GFG
{
static void printCase( int n)
{
if (n <= 2)
{
Console.Write(-1);
return ;
}
for ( int i = n; i >= 1; i--)
Console.Write(i + " " );
}
public static void Main()
{
int n = 3;
printCase(n);
}
}
|
PHP
<?php
function printCase( $n )
{
if ( $n <= 2)
{
echo (-1);
return ;
}
for ( $i = $n ; $i >= 1; $i --)
{
echo ( $i );
echo ( " " );
}
}
$n = 3;
printCase( $n );
?>
|
Javascript
<script>
function printCase(n)
{
if (n <= 2)
{
document.write(-1);
return ;
}
for (let i = n; i >= 1; i--)
document.write(i + " " );
}
let n = 3;
printCase(n);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)