打印给定排序算法在 C++ 中失效的案例
在这个问题中,我们得到了一个排序算法和一个数 n。我们的任务是打印一个 n 元素的数组,该数组不能被该算法排序。换句话说,算法将失效。
算法
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])
让我们看看这个排序算法,它使用了两个嵌套循环。外循环将从 1 到 n-1 运行,内循环将从 i 到 n-1 运行,并在每次迭代时检查内循环元素和外循环元素的值,并交换无序的元素。
所以当元素按相反的顺序排序时,这个算法将失效。此外,我们只能在 n<=2 时找到一个解决方案。
So, for n = 5. Output : 5 4 3 2 1 Time complexity − O(N)
示例
展示我们解决方案的实施的代码
#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;
}输出
在 6 个元素数组中,算法失效的情况是−
6 5 4 3 2 1
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP