📌  相关文章
📜  排列数组,以便在执行给定操作时获得升序

📅  最后修改于: 2021-04-29 13:39:37             🧑  作者: Mango

给定大小为N的数组arr [] ,任务是打印数组的排列,以便在对该排列执行以下操作时,获得递增顺序作为输出:

  1. 取第一个(0索引)元素,将其从数组中删除并打印。
  2. 如果数组中还有剩余元素,请将下一个顶部元素移到数组末尾。
  3. 重复上述步骤,直到数组不为空。

例子:

方法:
这个想法是模拟给定的过程。为此,使用队列数据结构。

  1. 给定的数组被排序,并通过添加数组索引来准备队列。
  2. 然后遍历给定的数组,对于每个元素,从队列前面的索引被弹出,然后将当前数组元素添加到结果数组中的弹出索引处。
  3. 如果队列仍然不为空,则将下一个索引(在队列的前面)移到队列的后面。

下面是上述方法的实现:

C++
#include 
#define mod 1000000007
using namespace std;
 
// Function to print the arrangement
vector arrangement(vector arr)
{
    // Sorting the list
    sort(arr.begin(), arr.end());
 
    // Finding Length of the List
    int length = arr.size();
 
    // Initializing the result array
    vector ans(length, 0);
 
    // Initializing the Queue
    deque Q;
    for (int i = 0; i < length; i++)
        Q.push_back(i);
 
    // Adding current array element to the
    // result at an index which is at the
    // front of the Q and then if still
    // elements are left then putting the next
    // top element the bottom of the array.
    for (int i = 0; i < length; i++)
    {
        int j = Q.front();
        Q.pop_front();
        ans[j] = arr[i];
 
        if (Q.size() != 0)
        {
            j = Q.front();
            Q.pop_front();
            Q.push_back(j);
        }
    }
    return ans;
}
 
// Driver code
int main()
{
    vector arr = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
    vector answer = arrangement(arr);
 
    for (int i : answer)
        cout << i << " ";
}
 
// This code is contributed by mohit kumar 29


Java
// Java implementation of the above approach
 
import java.util.*;
 
public class GfG
{
 
    // Function to find the array
    // arrangement
    static public int[] arrayIncreasing(int[] arr)
    {
 
        // Sorting the array
        Arrays.sort(arr);
 
        // Finding size of array
        int length = arr.length;
 
        // Empty array to store resultant order
        int answer[] = new int[length];
 
        // Doubly Ended Queue to
        // simulate the process
        Deque dq = new LinkedList<>();
 
        // Loop to initialize queue with indexes
        for (int i = 0; i < length; i++) {
            dq.add(i);
        }
 
        // Adding current array element to the
        // result at an index which is at the
        // front of the queue and then if still
        // elements are left then putting the next
        // top element the bottom of the array.
        for (int i = 0; i < length; i++)
        {
 
            answer[dq.pollFirst()] = arr[i];
 
            if (!dq.isEmpty())
                dq.addLast(dq.pollFirst());
        }
 
        // Returning the resultant order
        return answer;
    }
 
    // Driver code
    public static void main(String args[])
    {
        int A[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
        // Calling the function
        int ans[] = arrayIncreasing(A);
 
        // Printing the obtained pattern
        for (int i = 0; i < A.length; i++)
            System.out.print(ans[i] + " ");
    }
}


Python
# Python3 Code for the approach
 
# Importing Queue from Collections Module
from collections import deque
 
# Function to print the arrangement
def arrangement(arr):
    # Sorting the list
    arr.sort()
     
    # Finding Length of the List
    length = len(arr)
     
    # Initializing the result array
    answer = [0 for x in range(len(arr))]
     
    # Initializing the Queue
    queue = deque()
    for i in range(length):
        queue.append(i)
     
    # Adding current array element to the
    # result at an index which is at the
    # front of the queue and then if still
    # elements are left then putting the next
    # top element the bottom of the array.
    for i in range(length):
     
        answer[queue.popleft()] = arr[i]
     
        if len(queue) != 0:
            queue.append(queue.popleft())
    return answer
 
# Driver code
arr = [1, 2, 3, 4, 5, 6, 7, 8]
answer = arrangement(arr)
# Printing the obtained result
print(*answer, sep = ' ')


C#
// C# implementation of the above approach
using System;
using System.Collections.Generic;
 
class GfG
{
 
    // Function to find the array
    // arrangement
    static public int[] arrayIncreasing(int[] arr)
    {
 
        // Sorting the array
        Array.Sort(arr);
 
        // Finding size of array
        int length = arr.Length;
 
        // Empty array to store resultant order
        int []answer = new int[length];
 
        // Doubly Ended Queue to
        // simulate the process
        List dq = new List();
 
        // Loop to initialize queue with indexes
        for (int i = 0; i < length; i++)
        {
            dq.Add(i);
        }
 
        // Adding current array element to the
        // result at an index which is at the
        // front of the queue and then if still
        // elements are left then putting the next
        // top element the bottom of the array.
        for (int i = 0; i < length; i++)
        {
 
            answer[dq[0]] = arr[i];
            dq.RemoveAt(0);
            if (dq.Count != 0)
            {
                dq.Add(dq[0]);
                dq.RemoveAt(0);
            }
        }
 
        // Returning the resultant order
        return answer;
    }
 
    // Driver code
    public static void Main(String []args)
    {
        int []A = { 1, 2, 3, 4, 5, 6, 7, 8 };
 
        // Calling the function
        int []ans = arrayIncreasing(A);
 
        // Printing the obtained pattern
        for (int i = 0; i < A.Length; i++)
            Console.Write(ans[i] + " ");
    }
}
 
// This code is contributed by 29AjayKumar


C++
// C++ program to find the desired output
// after performing given operations
 
#include 
using namespace std;
// Function to arrange array in such a way
// that after performing given operation
// We get increasing sorted array
 
void Desired_Array(vector& v)
{
    // Size of given array
    int n = v.size();
 
    // Sort thr given array
    sort(v.begin(), v.end());
 
    // Start erasing last element and place it at
    // ith index
    int i = n - 1;
    // While we reach at starting
 
    while (i > 0) {
        // Store last element
        int p = v[n - 1];
 
        // Shift all elements by 1 position in right
        for (int j = n - 1; j >= i; j--)
        {
            v[j + 1] = v[j];
        }
 
        // insert last element at ith position
        v[i] = p;
        i--;
    }
 
    // print desired Array
    for (auto x : v)
        cout << x << " ";
    cout << "\n";
}
 
// Driver Code
int main()
{
 
    // Given Array
    vector v = { 1, 2, 3, 4, 5 };
    Desired_Array(v);
 
    vector v1 = { 1, 12, 2, 10, 4, 16, 6 };
    Desired_Array(v1);
    return 0;
}
 
// Contributed by ajaykr00kj


Java
// Java program to find the
// desired output after
// performing given operations
import java.util.Arrays;
class Main{
     
// Function to arrange array in
// such a way that after performing
// given operation We get increasing
// sorted array
public static void Desired_Array(int v[])
{
  // Size of given array
  int n = v.length;
 
  // Sort thr given array
  Arrays.sort(v);
 
  // Start erasing last element
  // and place it at ith index
  int i = n - 1;
   
  // While we reach at starting
  while (i > 0)
  {
    // Store last element
    int p = v[n - 1];
 
    // Shift all elements by
    // 1 position in right
    for (int j = n - 1;
             j >= i; j--)
    {
      v[j] = v[j - 1];
    }
 
    // insert last element at
    // ith position
    v[i] = p;
    i--;
  }
 
  // Print desired Array
  for(int x = 0; x < v.length; x++)
  {
    System.out.print(v[x] + " ");
  }
 
  System.out.println();
}
 
// Driver code   
public static void main(String[] args)
{
  // Given Array
  int v[] = {1, 2, 3, 4, 5};
  Desired_Array(v);
 
  int v1[] = {1, 12, 2, 10, 4, 16, 6};
  Desired_Array(v1);
}
}
 
// This code is contributed by divyeshrabadiya07


Python3
# Python3 program to find the desired output
# after performing given operations
 
# Function to arrange array in such a way
# that after performing given operation
# We get increasing sorted array
def Desired_Array(v):
 
    # Size of given array
    n = len(v)
 
    # Sort thr given array
    v.sort()
 
    # Start erasing last element and place it at
    # ith index
    i = n - 1
    # While we reach at starting
 
    while (i > 0) :
        # Store last element
        p = v[n - 1]
 
        # Shift all elements by 1 position in right
        for j in range(n-1, i - 1, -1) :
         
            v[j] = v[j - 1]
 
        # insert last element at ith position
        v[i] = p
        i -= 1
     
    # print desired Array
    for x in v :
        print(x, end = " ")
    print()
 
 
# Given Array
v = [ 1, 2, 3, 4, 5 ]
Desired_Array(v)
 
v1 = [ 1, 12, 2, 10, 4, 16, 6 ]
Desired_Array(v1)
 
# This code is contributed by divyesh072019


C#
// C# program to find the desired
// output after performing given
// operations
using System;
  
class GFG{
     
// Function to arrange array in
// such a way that after performing
// given operation We get increasing
// sorted array
public static void Desired_Array(int[] v)
{
     
    // Size of given array
    int n = v.Length;
     
    // Sort thr given array
    Array.Sort(v);
     
    // Start erasing last element
    // and place it at ith index
    int i = n - 1;
     
    // While we reach at starting
    while (i > 0)
    {
         
        // Store last element
        int p = v[n - 1];
         
        // Shift all elements by
        // 1 position in right
        for(int j = n - 1;
                j >= i; j--)
        {
            v[j] = v[j - 1];
        }
         
        // Insert last element at
        // ith position
        v[i] = p;
        i--;
    }
     
    // Print desired Array
    for(int x = 0; x < v.Length; x++)
    {
        Console.Write(v[x] + " ");
    }
     
    Console.WriteLine();
}
  
// Driver code       
static public void Main()
{
     
    // Given Array
    int[] v = { 1, 2, 3, 4, 5 };
    Desired_Array(v);
     
    int[] v1 = { 1, 12, 2, 10, 4, 16, 6 };
    Desired_Array(v1);
}
}
 
// This code is contributed by offbeat


Javascript


输出
1 5 2 7 3 6 4 8

时间复杂度: O(NlogN)
另一种方法:

如果您仔细观察它,就会发现它遵循一种模式。

只是想反向。

  • 对输入数组进行排序,并尝试从给定的步骤进入上一个阶段。
  • 通过在每个步骤中将i减1,从i = N-1迭代到1。
  • 从数组中删除最后一个元素,并将其插入第ith个位置。
  • 重复上述两步,直到达到i = 1
  • 达到i = 1后,您将获得最终的结果数组。

下面是上述方法的实现:

C++

// C++ program to find the desired output
// after performing given operations
 
#include 
using namespace std;
// Function to arrange array in such a way
// that after performing given operation
// We get increasing sorted array
 
void Desired_Array(vector& v)
{
    // Size of given array
    int n = v.size();
 
    // Sort thr given array
    sort(v.begin(), v.end());
 
    // Start erasing last element and place it at
    // ith index
    int i = n - 1;
    // While we reach at starting
 
    while (i > 0) {
        // Store last element
        int p = v[n - 1];
 
        // Shift all elements by 1 position in right
        for (int j = n - 1; j >= i; j--)
        {
            v[j + 1] = v[j];
        }
 
        // insert last element at ith position
        v[i] = p;
        i--;
    }
 
    // print desired Array
    for (auto x : v)
        cout << x << " ";
    cout << "\n";
}
 
// Driver Code
int main()
{
 
    // Given Array
    vector v = { 1, 2, 3, 4, 5 };
    Desired_Array(v);
 
    vector v1 = { 1, 12, 2, 10, 4, 16, 6 };
    Desired_Array(v1);
    return 0;
}
 
// Contributed by ajaykr00kj

Java

// Java program to find the
// desired output after
// performing given operations
import java.util.Arrays;
class Main{
     
// Function to arrange array in
// such a way that after performing
// given operation We get increasing
// sorted array
public static void Desired_Array(int v[])
{
  // Size of given array
  int n = v.length;
 
  // Sort thr given array
  Arrays.sort(v);
 
  // Start erasing last element
  // and place it at ith index
  int i = n - 1;
   
  // While we reach at starting
  while (i > 0)
  {
    // Store last element
    int p = v[n - 1];
 
    // Shift all elements by
    // 1 position in right
    for (int j = n - 1;
             j >= i; j--)
    {
      v[j] = v[j - 1];
    }
 
    // insert last element at
    // ith position
    v[i] = p;
    i--;
  }
 
  // Print desired Array
  for(int x = 0; x < v.length; x++)
  {
    System.out.print(v[x] + " ");
  }
 
  System.out.println();
}
 
// Driver code   
public static void main(String[] args)
{
  // Given Array
  int v[] = {1, 2, 3, 4, 5};
  Desired_Array(v);
 
  int v1[] = {1, 12, 2, 10, 4, 16, 6};
  Desired_Array(v1);
}
}
 
// This code is contributed by divyeshrabadiya07

Python3

# Python3 program to find the desired output
# after performing given operations
 
# Function to arrange array in such a way
# that after performing given operation
# We get increasing sorted array
def Desired_Array(v):
 
    # Size of given array
    n = len(v)
 
    # Sort thr given array
    v.sort()
 
    # Start erasing last element and place it at
    # ith index
    i = n - 1
    # While we reach at starting
 
    while (i > 0) :
        # Store last element
        p = v[n - 1]
 
        # Shift all elements by 1 position in right
        for j in range(n-1, i - 1, -1) :
         
            v[j] = v[j - 1]
 
        # insert last element at ith position
        v[i] = p
        i -= 1
     
    # print desired Array
    for x in v :
        print(x, end = " ")
    print()
 
 
# Given Array
v = [ 1, 2, 3, 4, 5 ]
Desired_Array(v)
 
v1 = [ 1, 12, 2, 10, 4, 16, 6 ]
Desired_Array(v1)
 
# This code is contributed by divyesh072019

C#

// C# program to find the desired
// output after performing given
// operations
using System;
  
class GFG{
     
// Function to arrange array in
// such a way that after performing
// given operation We get increasing
// sorted array
public static void Desired_Array(int[] v)
{
     
    // Size of given array
    int n = v.Length;
     
    // Sort thr given array
    Array.Sort(v);
     
    // Start erasing last element
    // and place it at ith index
    int i = n - 1;
     
    // While we reach at starting
    while (i > 0)
    {
         
        // Store last element
        int p = v[n - 1];
         
        // Shift all elements by
        // 1 position in right
        for(int j = n - 1;
                j >= i; j--)
        {
            v[j] = v[j - 1];
        }
         
        // Insert last element at
        // ith position
        v[i] = p;
        i--;
    }
     
    // Print desired Array
    for(int x = 0; x < v.Length; x++)
    {
        Console.Write(v[x] + " ");
    }
     
    Console.WriteLine();
}
  
// Driver code       
static public void Main()
{
     
    // Given Array
    int[] v = { 1, 2, 3, 4, 5 };
    Desired_Array(v);
     
    int[] v1 = { 1, 12, 2, 10, 4, 16, 6 };
    Desired_Array(v1);
}
}
 
// This code is contributed by offbeat

Java脚本


输出
1 5 2 4 3 
1 12 2 10 4 16 6