📜  打印给定排序算法失败的情况

📅  最后修改于: 2021-06-26 19:32:41             🧑  作者: Mango

给定整数N,任务是查找未通过以下排序算法的N个元素。如果N个元素均未失败,则打印-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])

例子:

Input: N = 10 
Output: 10 9 8 7 6 5 4 3 2 1 

Input: N = 2
Output: -1

方法:在解决各种情况时,我们可以观察到仅对于n <= 2 ,给定的算法是无效的。大于N的任何值将在给定算法上失败。使用此给定算法无法对由N个数字(1、2、3 …. N)组成的排序数组进行反向排序。
下面是上述方法的实现:

C++
// C++ program to find a case where the
// given algorithm fails
 
#include 
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
= 1; $i--)
    {
        echo ($i);
        echo(" ");
    }
}
 
// Driver Code
$n = 3;
 
printCase($n);
 
// This code is contributed
// by Shivi_Aggarwal
?>


Javascript


输出:
3 2 1

时间复杂度:O(N)
辅助空间:O(1)

如果您希望与行业专家一起参加现场课程,请参阅《 Geeks现场课程》和《 Geeks现场课程美国》。