Dada una array arr[] que consta de 2* N elementos en forma de { a 1 , a 2 , …, a N , b 1 , b 2 , …, b N } , la tarea es barajar la array a {a 1 , b 1 , a 2 , b 2 , …, a n , b 1 } sin usar espacio adicional.
Ejemplos :
Entrada: arr[] = { 1, 3, 5, 2, 4, 6 }
Salida: 1 2 3 4 5 6
Explicación:
La salida contiene los elementos en forma de { a 1 , b 1 , a 2 , b 2 , a 3 , b 3 }.Entrada: arr[] = {1, 2, 3, -1, -2, -3, }
Salida: 1 -1 2 -2 3 -3
Enfoque basado en divide y vencerás: si el tamaño de una array es una potencia de 2 , entonces sigue el artículo Baraja 2n enteros en formato {a1, b1, a2, b2, a3, b3, ……, an, bn} usando divide y conquistar la técnica.
Complejidad de tiempo: O(N * log(N))
Espacio auxiliar: O(1)
Enfoque alternativo: el enfoque anterior funcionará para todos los valores posibles de N dividiendo recursivamente la array de manera que la longitud de ambas mitades sea uniforme. Siga los pasos a continuación para resolver el problema:
- Defina una función recursiva, digamos shuffle(start, end) .
- Si la longitud de la array es divisible por 4 , calcule el punto medio de la array, digamos mid = start + (end – start + 1) / 2.
- De lo contrario, mid = start + (end – start + 1) / 2 – 1.
- Calcule los puntos medios de ambos subarreglos, digamos mid1 = start + (mid – start)/2 , y mid2 = mid + (end – mid + 1) / 2.
- Invierta los subarreglos en los rangos [mid1, mid2], [mid1, mid-1] y [mid, mid2 – 1].
- Realice llamadas recursivas para los subarreglos [start, mid – 1] y [mid, end] , es decir, shuffle(start, mid – 1) y shuffle(mid, end) respectivamente.
- Finalmente, imprima la array .
Ilustración:
Considere una array arr[] = {a1, a2, a3, b1, b2, b3}:
- Divida la array en dos mitades, ambas de igual longitud, es decir, a1, a2 : a3, b1, b2, b3.
- Invierta la mitad de la primera mitad a la mitad de la segunda mitad, es decir, a1, b1 : a3, a2, b2, b3.
- Ahora, invierta la mitad de la primera mitad a la mitad del subarreglo [0, 5], a1, b1 : a3, a2, b2, b3.
- Ahora invierta la mitad del subarreglo [0, 5] a la mitad de la segunda mitad, a1, b1 : a2, a3, b2, b3.
- Llame recursivamente a las arrays {a1, b1} y {a2, a3, b2, b3} .
- Ahora la array {a2, a3, b2, b3} se modifica a {a2, b2, a3, b3} después de aplicar las operaciones anteriores.
- Ahora el arr[] se modifica a {a1, b1, a2, b2, a3, b3} .
A continuación se muestra la implementación del enfoque anterior:
C
// C program for the above approach #include <stdio.h> // Function to reverse the array from the // position 'start' to position 'end' void reverse(int arr[], int start, int end) { // Stores mid of start and end int mid = (end - start + 1) / 2; // Traverse the array in // the range [start, end] for (int i = 0; i < mid; i++) { // Stores arr[start + i] int temp = arr[start + i]; // Update arr[start + i] arr[start + i] = arr[end - i]; // Update arr[end - i] arr[end - i] = temp; } return; } // Utility function to shuffle the given array // in the of form {a1, b1, a2, b2, ....an, bn} void shuffleArrayUtil(int arr[], int start, int end) { int i; // Stores the length of the array int l = end - start + 1; // If length of the array is 2 if (l == 2) return; // Stores mid of the { start, end } int mid = start + l / 2; // Divide array into two // halves of even length if (l % 4) { // Update mid mid -= 1; } // Calculate the mid-points of // both halves of the array int mid1 = start + (mid - start) / 2; int mid2 = mid + (end + 1 - mid) / 2; // Reverse the subarray made // from mid1 to mid2 reverse(arr, mid1, mid2 - 1); // Reverse the subarray made // from mid1 to mid reverse(arr, mid1, mid - 1); // Reverse the subarray made // from mid to mid2 reverse(arr, mid, mid2 - 1); // Recursively calls for both // the halves of the array shuffleArrayUtil(arr, start, mid - 1); shuffleArrayUtil(arr, mid, end); } // Function to shuffle the given array in // the form of {a1, b1, a2, b2, ....an, bn} void shuffleArray(int arr[], int N, int start, int end) { // Function Call shuffleArrayUtil(arr, start, end); // Print the modified array for (int i = 0; i < N; i++) printf("%d ", arr[i]); } // Driver Code int main() { // Given array int arr[] = { 1, 3, 5, 2, 4, 6 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Shuffles the given array to the // required permutation shuffleArray(arr, N, 0, N - 1); return 0; }
C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to reverse the array from the // position 'start' to position 'end' void reverse(int arr[], int start, int end) { // Stores mid of start and end int mid = (end - start + 1) / 2; // Traverse the array in // the range [start, end] for (int i = 0; i < mid; i++) { // Stores arr[start + i] int temp = arr[start + i]; // Update arr[start + i] arr[start + i] = arr[end - i]; // Update arr[end - i] arr[end - i] = temp; } return; } // Utility function to shuffle the given array // in the of form {a1, b1, a2, b2, ....an, bn} void shuffleArrayUtil(int arr[], int start, int end) { int i; // Stores the length of the array int l = end - start + 1; // If length of the array is 2 if (l == 2) return; // Stores mid of the { start, end } int mid = start + l / 2; // Divide array into two // halves of even length if (l % 4) { // Update mid mid -= 1; } // Calculate the mid-points of // both halves of the array int mid1 = start + (mid - start) / 2; int mid2 = mid + (end + 1 - mid) / 2; // Reverse the subarray made // from mid1 to mid2 reverse(arr, mid1, mid2 - 1); // Reverse the subarray made // from mid1 to mid reverse(arr, mid1, mid - 1); // Reverse the subarray made // from mid to mid2 reverse(arr, mid, mid2 - 1); // Recursively calls for both // the halves of the array shuffleArrayUtil(arr, start, mid - 1); shuffleArrayUtil(arr, mid, end); } // Function to shuffle the given array in // the form of {a1, b1, a2, b2, ....an, bn} void shuffleArray(int arr[], int N, int start, int end) { // Function Call shuffleArrayUtil(arr, start, end); // Print the modified array for (int i = 0; i < N; i++) cout << arr[i] << " "; } // Driver Code int main() { // Given array int arr[] = { 1, 3, 5, 2, 4, 6 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); // Shuffles the given array to the // required permutation shuffleArray(arr, N, 0, N - 1); return 0; } // This code is contributed by jainlovely450.
Java
// Java program for the above approach class GFG{ // Function to reverse the array from the // position 'start' to position 'end' static void reverse(int arr[], int start, int end) { // Stores mid of start and end int mid = (end - start + 1) / 2; // Traverse the array in // the range [start, end] for (int i = 0; i < mid; i++) { // Stores arr[start + i] int temp = arr[start + i]; // Update arr[start + i] arr[start + i] = arr[end - i]; // Update arr[end - i] arr[end - i] = temp; } return; } // Utility function to shuffle the given array // in the of form {a1, b1, a2, b2, ....an, bn} static void shuffleArrayUtil(int arr[], int start, int end) { int i; // Stores the length of the array int l = end - start + 1; // If length of the array is 2 if (l == 2) return; // Stores mid of the { start, end } int mid = start + l / 2; // Divide array into two // halves of even length if (l % 4 > 0) { // Update mid mid -= 1; } // Calculate the mid-points of // both halves of the array int mid1 = start + (mid - start) / 2; int mid2 = mid + (end + 1 - mid) / 2; // Reverse the subarray made // from mid1 to mid2 reverse(arr, mid1, mid2 - 1); // Reverse the subarray made // from mid1 to mid reverse(arr, mid1, mid - 1); // Reverse the subarray made // from mid to mid2 reverse(arr, mid, mid2 - 1); // Recursively calls for both // the halves of the array shuffleArrayUtil(arr, start, mid - 1); shuffleArrayUtil(arr, mid, end); } // Function to shuffle the given array in // the form of {a1, b1, a2, b2, ....an, bn} static void shuffleArray(int arr[], int N, int start, int end) { // Function Call shuffleArrayUtil(arr, start, end); // Print the modified array for (int i = 0; i < N; i++) System.out.printf("%d ", arr[i]); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 1, 3, 5, 2, 4, 6 }; // Size of the array int N = arr.length; // Shuffles the given array to the // required permutation shuffleArray(arr, N, 0, N - 1); } } // This code is contributed by 29AjayKumar
Python3
# Python3 program for the above approach # Function to reverse the array from the # position 'start' to position 'end' def reverse(arr, start, end): # Stores mid of start and end mid = (end - start + 1) // 2 # Traverse the array in # the range [start, end] for i in range(mid): # Stores arr[start + i] temp = arr[start + i] # Update arr[start + i] arr[start + i] = arr[end - i] # Update arr[end - i] arr[end - i] = temp return arr # Utility function to shuffle the given array # in the of form {a1, b1, a2, b2, ....an, bn} def shuffleArrayUtil(arr, start, end): i = 0 # Stores the length of the array l = end - start + 1 # If length of the array is 2 if (l == 2): return # Stores mid of the { start, end } mid = start + l // 2 # Divide array into two # halves of even length if (l % 4): # Update mid mid -= 1 # Calculate the mid-points of # both halves of the array mid1 = start + (mid - start) // 2 mid2 = mid + (end + 1 - mid) // 2 # Reverse the subarray made # from mid1 to mid2 arr = reverse(arr, mid1, mid2 - 1) # Reverse the subarray made # from mid1 to mid arr = reverse(arr, mid1, mid - 1) # Reverse the subarray made # from mid to mid2 arr = reverse(arr, mid, mid2 - 1) # Recursively calls for both # the halves of the array shuffleArrayUtil(arr, start, mid - 1) shuffleArrayUtil(arr, mid, end) # Function to shuffle the given array in # the form of {a1, b1, a2, b2, ....an, bn} def shuffleArray(arr, N, start, end): # Function Call shuffleArrayUtil(arr, start, end) # Print the modified array for i in arr: print(i, end=" ") # Driver Code if __name__ == '__main__': # Given array arr = [1, 3, 5, 2, 4, 6] # Size of the array N = len(arr) # Shuffles the given array to the # required permutation shuffleArray(arr, N, 0, N - 1) # This code is contributed by mohit kumar 29
C#
// C# program for the above approach using System; public class GFG{ // Function to reverse the array from the // position 'start' to position 'end' static void reverse(int[] arr, int start, int end) { // Stores mid of start and end int mid = (end - start + 1) / 2; // Traverse the array in // the range [start, end] for (int i = 0; i < mid; i++) { // Stores arr[start + i] int temp = arr[start + i]; // Update arr[start + i] arr[start + i] = arr[end - i]; // Update arr[end - i] arr[end - i] = temp; } return; } // Utility function to shuffle the given array // in the of form {a1, b1, a2, b2, ....an, bn} static void shuffleArrayUtil(int[] arr, int start, int end) { // Stores the length of the array int l = end - start + 1; // If length of the array is 2 if (l == 2) return; // Stores mid of the { start, end } int mid = start + l / 2; // Divide array into two // halves of even length if (l % 4 > 0) { // Update mid mid -= 1; } // Calculate the mid-points of // both halves of the array int mid1 = start + (mid - start) / 2; int mid2 = mid + (end + 1 - mid) / 2; // Reverse the subarray made // from mid1 to mid2 reverse(arr, mid1, mid2 - 1); // Reverse the subarray made // from mid1 to mid reverse(arr, mid1, mid - 1); // Reverse the subarray made // from mid to mid2 reverse(arr, mid, mid2 - 1); // Recursively calls for both // the halves of the array shuffleArrayUtil(arr, start, mid - 1); shuffleArrayUtil(arr, mid, end); } // Function to shuffle the given array in // the form of {a1, b1, a2, b2, ....an, bn} static void shuffleArray(int[] arr, int N, int start, int end) { // Function Call shuffleArrayUtil(arr, start, end); // Print the modified array for (int i = 0; i < N; i++) Console.Write(arr[i] + " "); } // Driver Code static public void Main () { // Given array int[] arr = { 1, 3, 5, 2, 4, 6 }; // Size of the array int N = arr.Length; // Shuffles the given array to the // required permutation shuffleArray(arr, N, 0, N - 1); } } // This code is contributed by Dharanendra L V
Javascript
<script> // Javascript program of the above approach // Function to reverse the array from the // position 'start' to position 'end' function reverse(arr, start, end) { // Stores mid of start and end let mid = (end - start + 1) / 2; // Traverse the array in // the range [start, end] for (let i = 0; i < mid; i++) { // Stores arr[start + i] let temp = arr[start + i]; // Update arr[start + i] arr[start + i] = arr[end - i]; // Update arr[end - i] arr[end - i] = temp; } return; } // Utility function to shuffle the given array // in the of form {a1, b1, a2, b2, ....an, bn} function shuffleArrayUtil(arr, start, end) { let i; // Stores the length of the array let l = end - start + 1; // If length of the array is 2 if (l == 2) return; // Stores mid of the { start, end } let mid = start + l / 2; // Divide array into two // halves of even length if (l % 4 > 0) { // Update mid mid -= 1; } // Calculate the mid-points of // both halves of the array let mid1 = start + (mid - start) / 2; let mid2 = mid + (end + 1 - mid) / 2; // Reverse the subarray made // from mid1 to mid2 reverse(arr, mid1, mid2 - 1); // Reverse the subarray made // from mid1 to mid reverse(arr, mid1, mid - 1); // Reverse the subarray made // from mid to mid2 reverse(arr, mid, mid2 - 1); // Recursively calls for both // the halves of the array shuffleArrayUtil(arr, start, mid - 1); shuffleArrayUtil(arr, mid, end); } // Function to shuffle the given array in // the form of {a1, b1, a2, b2, ....an, bn} function shuffleArray(arr, N, start, end) { // Function Call shuffleArrayUtil(arr, start, end); // Print the modified array for (let i = 0; i < N; i++) document.write(arr[i] + " "); } // Driver Code // Given array let arr = [ 1, 3, 5, 2, 4, 6 ]; // Size of the array let N = arr.length; // Shuffles the given array to the // required permutation shuffleArray(arr, N, 0, N - 1); </script>
1 2 3 4 5 6
Complejidad de tiempo : O(N * log(N))
Espacio auxiliar: O(1)