Ordenar cuadrados perfectos en una array en sus posiciones relativas

Dada una array de enteros  Arr, la tarea es ordenar solo los elementos que son cuadrados perfectos en sus posiciones relativas en la array (las posiciones de otros elementos no deben verse afectadas).
Ejemplos: 
 

Entrada: arr[] = {2, 64, 9, 8, 1, 4} 
Salida: 2 1 4 8 9 64 
1, 4, 9 y 64 son los únicos cuadrados perfectos de la array.
Entrada: arr[] = {1, 49, 2, 36} 
Salida: 1 36 2 49 
 

Acercarse: 
 

  • Inicialice dos vectores vacíos y recorra la array de izquierda a derecha.
  • Tome un número entero y una variable flotante y para cada elemento de la array almacene su raíz cuadrada en ambas variables.
  • Si ambas variables son iguales, empuje el índice de este elemento en el primer vector y empuje el elemento mismo en el segundo vector.
  • Ordenar el segundo vector.
  • Ahora, tenemos el índice de todos los elementos requeridos en el primer vector y también todos los elementos requeridos ordenados en el segundo vector.
  • Entonces, inserte los elementos del segundo vector en la array en los índices presentes en el primer vector uno por uno.

A continuación se muestra la implementación del enfoque anterior: 
 

C++

// C++ program to sort all the elements that are
// perfect squares in their relative positions
#include <bits/stdc++.h>
using namespace std;
 
// function to sort all the elements that are
// perfect squares in their relative positions
void sortPerfectSquare(int arr[], int n)
{
    int a;
    float b;
 
    // v1 will contain index of perfect squares
    // v2 will contain each perfect square
    vector<int> v1;
    vector<int> v2;
 
    for (int i = 0; i < n; i++) {
        b = sqrt(arr[i]);
        a = b;
 
        // if both a and b are equal then
        // arr[i] is a perfect square
        if (a == b) {
            v1.push_back(i);
            v2.push_back(arr[i]);
        }
    }
 
    // sort second vector
    sort(v2.begin(), v2.end());
 
    // put the sorted perfect square
    // back into the array
    int j = 0;
    for (int i = 0; i < n; i++) {
        if (v1[j] == i) {
            arr[i] = v2[j];
            j++;
        }
    }
 
    // print final array
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 9, 44, 100, 81, 21, 64 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    sortPerfectSquare(arr, n);
 
    return 0;
}

Java

// Java program to sort all the elements that are
// perfect squares in their relative positions
import java.util.*;
 
class GFG
{
 
// function to sort all the elements that are
// perfect squares in their relative positions
static void sortPerfectSquare(int arr[], int n)
{
    int a;
    float b;
 
    // v1 will contain index of perfect squares
    // v2 will contain each perfect square
    Vector<Integer> v1 = new Vector<Integer>();
    Vector<Integer> v2 = new Vector<Integer>();
 
    for (int i = 0; i < n; i++)
    {
        b = (float) Math.sqrt(arr[i]);
        a = (int) b;
 
        // if both a and b are equal then
        // arr[i] is a perfect square
        if (a == b)
        {
            v1.add(i);
            v2.add(arr[i]);
        }
    }
 
    // sort second vector
    Collections.sort(v2);
 
    // put the sorted perfect square
    // back into the array
    int j = 0;
    for (int i = 0; i < n; i++)
    {
        if (v1.get(j) == i)
        {
            arr[i] = v2.get(j);
            j++;
        }
    }
 
    // print final array
    for (int i = 0; i < n; i++)
            System.out.print(arr[i]+" ");
}
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 9, 44, 100, 81, 21, 64 };
        int n = arr.length;
 
        sortPerfectSquare(arr, n);
    }
}
 
// This code is contributed by 29AjayKumar

Python3

# Python 3 program to sort all
# the elements that are perfect
# squares in their relative positions
 
# import sqrt() from math lib
from math import sqrt
 
# function to sort all the elements
# that are perfect squares in their
# relative positions
def sortPerfectSquare(arr, n) :
     
    # v1 will contain index of
    # perfect squares and v2 will
    # contain each perfect square
    v1 = []
    v2 = []
     
    for i in range(n):
        b = sqrt(arr[i])
        a = int(b)
         
        # if both a and b are equal then
        # arr[i] is a perfect square
        if a == b :
            v1.append(i)
            v2.append(arr[i])
     
    # sort second list
    v2.sort()
     
    j = 0
     
    # put the sorted perfect square
    # back into the array
    for i in range(n) :
        if v1[j] == i :
            arr[i] = v2[j]
            j += 1
     
    # print final array
    for i in range(n) :
        print(arr[i], end = " ")
         
# Driver code
if __name__ == "__main__" :
    arr = [9, 44, 100, 81, 21, 64]
    n = len(arr)
     
    sortPerfectSquare(arr, n);
 
# This code is contributed by ANKITRAI1

C#

// C# program to sort all the elements that are
// perfect squares in their relative positions
using System;
using System.Collections.Generic;
 
class GFG
{
 
// function to sort all the elements that are
// perfect squares in their relative positions
static void sortPerfectSquare(int []arr, int n)
{
    int a;
    float b;
 
    // v1 will contain index of perfect squares
    // v2 will contain each perfect square
    List<int> v1 = new List<int>();
    List<int>v2 = new List<int>();
 
    for (int i = 0; i < n; i++)
    {
        b = (float) Math.Sqrt(arr[i]);
        a = (int) b;
 
        // if both a and b are equal then
        // arr[i] is a perfect square
        if (a == b)
        {
            v1.Add(i);
            v2.Add(arr[i]);
        }
    }
 
    // sort second vector
    v2.Sort();
 
    // put the sorted perfect square
    // back into the array
    int j = 0;
    for (int i = 0; i < n; i++)
    {
        if (v1[j] == i)
        {
            arr[i] = v2[j];
            j++;
        }
    }
 
    // print final array
    for (int i = 0; i < n; i++)
            Console.Write(arr[i] + " ");
}
 
// Driver code
public static void Main(String[] args)
{
    int []arr = { 9, 44, 100, 81, 21, 64 };
    int n = arr.Length;
 
    sortPerfectSquare(arr, n);
}
}
 
// This code is contributed by
// PrinciRaj1992

PHP

<?php
// PHP program to sort all the elements that are
// perfect squares in their relative positions
 
// function to sort all the elements that are
// perfect squares in their relative positions
function sortPerfectSquare($arr, $n)
{
    // v1 will contain index of perfect squares
    // v2 will contain each perfect square
    $v1 = array();
    $v2 = array();
 
    for ( $i = 0; $i < $n; $i++)
    {
        $b = sqrt($arr[$i]);
        $a = (int)$b;
 
        // if both a and b are equal then
        // arr[i] is a perfect square
        if ($a == $b)
        {
            array_push($v1, $i);
            array_push($v2, $arr[$i]);
        }
    }
 
    // sort second vector
    sort($v2);
 
    // put the sorted perfect square
    // back into the array
    $j = 0;
    for ( $i = 0; $i < $n; $i++)
    {
        if ($v1[$j] == $i)
        {
            $arr[$i] = $v2[$j];
            $j++;
        }
    }
 
    // print final array
    for ($i = 0; $i < $n; $i++)
        echo $arr[$i] . " ";
}
 
// Driver Code
$arr = array( 9, 44, 100, 81, 21, 64 );
$n = count($arr);
sortPerfectSquare($arr, $n);
 
// This code is contributed by Rajput-Ji
?>

Javascript

<script>
 
// Javascript program to sort all the elements that are
// perfect squares in their relative positions
 
// function to sort all the elements that are
// perfect squares in their relative positions
function sortPerfectSquare(arr, n)
{
    var a;
    var b;
 
    // v1 will contain index of perfect squares
    // v2 will contain each perfect square
    var v1 = [];
    var v2 = [];
 
    for (var i = 0; i < n; i++) {
        b = Math.sqrt(arr[i]);
        a = parseInt(b);
 
        // if both a and b are equal then
        // arr[i] is a perfect square
        if (a == b) {
            v1.push(i);
            v2.push(arr[i]);
        }
    }
 
    // sort second vector
    v2.sort((a,b) => a-b)
 
    // put the sorted perfect square
    // back into the array
    var j = 0;
    for (var i = 0; i < n; i++) {
        if (v1[j] == i) {
            arr[i] = v2[j];
            j++;
        }
    }
 
    // print final array
    for (var i = 0; i < n; i++)
        document.write( arr[i] + " ");
}
 
// Driver code
var arr = [9, 44, 100, 81, 21, 64 ];
var n = arr.length;
sortPerfectSquare(arr, n);
 
</script>
Producción: 

9 44 64 81 21 100

 

Publicación traducida automáticamente

Artículo escrito por Shashank_Sharma y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *