📌  相关文章
📜  C ++程序检查是否可以在旋转后对数组进行排序

📅  最后修改于: 2022-05-13 01:55:34.991000             🧑  作者: Mango

C ++程序检查是否可以在旋转后对数组进行排序

给定一个大小为 N 的数组,任务是确定是否可以仅通过一次 shuffle 对数组进行排序。在一次 shuffle 中,我们可以将一些连续的元素从数组的末尾移动到数组的前面。
例如:

例子:

Input: arr[] = {1, 2, 3, 4} 
Output: Possible 
Since this array is already sorted hence no need for shuffle.

Input: arr[] = {6, 8, 1, 2, 5}
Output: Possible
Place last three elements at the front 
in the same order i.e. {1, 2, 5, 6, 8}

方法:

  1. 检查数组是否已经排序。如果是,则返回 true。
  2. 否则开始遍历数组元素,直到当前元素小于下一个元素。将该索引存储在 arr[i] > arr[i+1] 的位置。
  3. 从该点遍历并检查该索引中的元素是否按升序排列。
  4. 如果满足以上两个条件,则检查最后一个元素是否小于或等于给定数组的第一个元素。
  5. 如果满足以上三个条件,则打印“可能”,如果以上三个条件中的任何一个不满足,则打印“不可能”。

以下是上述方法的实现:

C++
// C++ implementation of above approach
#include 
using namespace std;
 
// Function to check if it is possible
bool isPossible(int a[], int n)
{
    // step 1
    if (is_sorted(a, a + n)) {
        cout << "Possible" << endl;
    }
 
    else {
 
        // break where a[i] > a[i+1]
        bool flag = true;
        int i;
        for (i = 0; i < n - 1; i++) {
            if (a[i] > a[i + 1]) {
                break;
            }
        }
        // break point + 1
        i++;
 
        // check whether the sequence is
        // further increasing or not
        for (int k = i; k < n - 1; k++) {
            if (a[k] > a[k + 1]) {
                flag = false;
                break;
            }
        }
 
        // If not increasing after break point
        if (!flag)
            return false;
 
        else {
 
            // last element <= First element
            if (a[n - 1] <= a[0])
                return true;
 
            else
                return false;
        }
    }
}
 
// Driver code
int main()
{
 
    int arr[] = { 3, 1, 2, 2, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    if (isPossible(arr, n))
        cout << "Possible";
 
    else
        cout << "Not Possible";
 
    return 0;
}


输出:
Possible

时间复杂度: O(n)

辅助空间: O(1)

请参阅完整的文章检查是否可以在旋转后对数组进行排序以获取更多详细信息!