列印給定排序演算法在 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

更新於:27-1 月-2020

74 次瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.