Modify an array by sorting after reversal of bits of each array element
Last Updated :
19 Jan, 2023
Given an array arr[] consisting of N integers, the task is to modify the array by replacing each array element with the number obtained by reversing their respective binary representations and sort the modified array.
Examples:
Input: arr[ ] = {43, 422, 132}
Output: 33 53 203
Explanation:
The binary representation of the array elements are {101011, 110100110, 10000100}.
Reversed binary representations are {110101, 011001011, 0010000}.
Equivalent numeric values of the reversed binary representations are {53, 203, 33}.
Sorted order of these elements are {33, 53, 203}.
Input: arr[ ] ={ 98, 43, 66, 83}
Output: 33 35 53 101
Approach: Follow the steps below to solve the problem:
Below is the implementation of the above approach:
C++14
// C++ implementation of
// the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to convert binary
// number to equivalent decimal
int binaryToDecimal(string n)
{
string num = n;
int dec_value = 0;
// Set base value to 1, i.e 2^0
int base = 1;
int len = num.length();
for (int i = len - 1; i >= 0; i--) {
if (num[i] == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
// Function to convert a decimal
// to equivalent binary representation
string decimalToBinary(int n)
{
// Stores the binary representation
string binstr = "";
while (n > 0) {
// Since ASCII value of
// '0', '1' are 48 and 49
binstr += (n % 2 + 48);
n = n / 2;
}
// As the string is already reversed,
// no further reversal is required
return binstr;
}
// Function to convert the reversed binary
// representation to equivalent integer
int reversedBinaryDecimal(int N)
{
// Stores reversed binary
// representation of given decimal
string decimal_to_binar
= decimalToBinary(N);
// Stores equivalent decimal
// value of the binary representation
int binary_to_decimal
= binaryToDecimal(decimal_to_binar);
// Return the resultant integer
return binary_to_decimal;
}
// Utility function to print the sorted array
void printSortedArray(int arr[], int size)
{
// Sort the array
sort(arr, arr + size);
// Traverse the array
for (int i = 0; i < size; i++)
// Print the array elements
cout << arr[i] << " ";
cout << endl;
}
// Utility function to reverse the
// binary representations of all
// array elements and sort the modified array
void modifyArray(int arr[], int size)
{
// Traverse the array
for (int i = 0; i < size; i++) {
// Passing array elements to
// reversedBinaryDecimal function
arr[i] = reversedBinaryDecimal(
arr[i]);
}
// Pass the array to
// the sorted array
printSortedArray(arr, size);
}
// Driver Code
int main()
{
int arr[] = { 98, 43, 66, 83 };
int n = sizeof(arr) / sizeof(arr[0]);
modifyArray(arr, n);
return 0;
}
Java
// Java implementation of
// the above approach
import java.io.*;
import java.util.*;
class GFG{
// Function to convert binary
// number to equivalent decimal
static int binaryToDecimal(String n)
{
String num = n;
int dec_value = 0;
// Set base value to 1, i.e 2^0
int base = 1;
int len = num.length();
for(int i = len - 1; i >= 0; i--)
{
if (num.charAt(i) == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
// Function to convert a decimal
// to equivalent binary representation
static String decimalToBinary(int n)
{
// Stores the binary representation
String binstr = "";
while (n > 0)
{
// Since ASCII value of
// '0', '1' are 48 and 49
binstr += (char)(n % 2 + 48);
n = n / 2;
}
// As the string is already reversed,
// no further reversal is required
return binstr;
}
// Function to convert the reversed binary
// representation to equivalent integer
static int reversedBinaryDecimal(int N)
{
// Stores reversed binary
// representation of given decimal
String decimal_to_binar = decimalToBinary(N);
// Stores equivalent decimal
// value of the binary representation
int binary_to_decimal = binaryToDecimal(
decimal_to_binar);
// Return the resultant integer
return binary_to_decimal;
}
// Utility function to print the sorted array
static void printSortedArray(int arr[], int size)
{
// Sort the array
Arrays.sort(arr);
// Traverse the array
for(int i = 0; i < size; i++)
// Print the array elements
System.out.print(arr[i] + " ");
System.out.println();
}
// Utility function to reverse the
// binary representations of all
// array elements and sort the modified array
static void modifyArray(int arr[], int size)
{
// Traverse the array
for(int i = 0; i < size; i++)
{
// Passing array elements to
// reversedBinaryDecimal function
arr[i] = reversedBinaryDecimal(arr[i]);
}
// Pass the array to
// the sorted array
printSortedArray(arr, size);
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 98, 43, 66, 83 };
int n = arr.length;
modifyArray(arr, n);
}
}
// This code is contributed by rag2127
Python3
# Python3 implementation of
# the above approach
# Function to convert binary
# number to equivalent decimal
def binaryToDecimal(n):
num = n
dec_value = 0
# Set base value to 1, i.e 2^0
base = 1
length = len(num)
for i in range(length - 1, -1, -1):
if (num[i] == '1'):
dec_value += base
base = base * 2
return dec_value
# Function to convert a decimal
# to equivalent binary representation
def decimalToBinary(n):
# Stores the binary representation
binstr = ""
while (n > 0):
# Since ASCII value of
# '0', '1' are 48 and 49
binstr += chr(n % 2 + 48)
n = n // 2
# As the string is already reversed,
# no further reversal is required
return binstr
# Function to convert the reversed binary
# representation to equivalent integer
def reversedBinaryDecimal(N):
# Stores reversed binary
# representation of given decimal
decimal_to_binar = decimalToBinary(N)
# Stores equivalent decimal
# value of the binary representation
binary_to_decimal = binaryToDecimal(
decimal_to_binar)
# Return the resultant integer
return binary_to_decimal
# Utility function to print the sorted array
def printSortedArray(arr, size):
# Sort the array
arr.sort()
# Traverse the array
for i in range(size):
# Print the array elements
print(arr[i], end=" ")
print()
# Utility function to reverse the
# binary representations of all
# array elements and sort the modified array
def modifyArray(arr, size):
# Traverse the array
for i in range(size):
# Passing array elements to
# reversedBinaryDecimal function
arr[i] = reversedBinaryDecimal(arr[i])
# Pass the array to
# the sorted array
printSortedArray(arr, size)
# Driver Code
if __name__ == "__main__":
arr = [ 98, 43, 66, 83 ]
n = len(arr)
modifyArray(arr, n)
# This code is contributed by ukasp
JavaScript
<script>
// Javascript implementation of
// the above approach
// Function to convert binary
// number to equivalent decimal
function binaryToDecimal(n)
{
let num = n;
let dec_value = 0;
// Set base value to 1, i.e 2^0
let base = 1;
let len = num.length;
for(let i = len - 1; i >= 0; i--)
{
if (num[i] == '1')
dec_value += base;
base = base * 2;
}
return dec_value;
}
// Function to convert a decimal
// to equivalent binary representation
function decimalToBinary(n)
{
// Stores the binary representation
let binstr = "";
while (n > 0)
{
// Since ASCII value of
// '0', '1' are 48 and 49
binstr += String.fromCharCode(n % 2 + 48);
n = Math.floor(n / 2);
}
// As the string is already reversed,
// no further reversal is required
return binstr;
}
// Function to convert the reversed binary
// representation to equivalent integer
function reversedBinaryDecimal(N)
{
// Stores reversed binary
// representation of given decimal
let decimal_to_binar = decimalToBinary(N);
// Stores equivalent decimal
// value of the binary representation
let binary_to_decimal = binaryToDecimal(
decimal_to_binar);
// Return the resultant integer
return binary_to_decimal;
}
// Utility function to print the sorted array
function printSortedArray(arr, size)
{
// Sort the array
arr.sort(function(a, b){return a - b;});
// Traverse the array
for(let i = 0; i < size; i++)
// Print the array elements
document.write(arr[i] + " ");
document.write("<br>")
}
// Utility function to reverse the
// binary representations of all
// array elements and sort the modified array
function modifyArray(arr, size)
{
// Traverse the array
for(let i = 0; i < size; i++)
{
// Passing array elements to
// reversedBinaryDecimal function
arr[i] = reversedBinaryDecimal(
arr[i]);
}
// Pass the array to
// the sorted array
printSortedArray(arr, size);
}
// Driver Code
let arr = [ 98, 43, 66, 83 ];
let n = arr.length;
modifyArray(arr, n);
// This code is contributed by avanitrachhadiya2155
</script>
C#
using System;
using System.Linq;
class GFG
{
// Function to convert binary
// number to equivalent decimal
static int BinaryToDecimal(string n)
{
string num = n;
int dec_value = 0;
// Set base1 value to 1, i.e 2^0
int base1 = 1;
int len = num.Length;
for (int i = len - 1; i >= 0; i--)
{
if (num[i] == '1')
dec_value += base1;
base1 = base1 * 2;
}
return dec_value;
}
// Function to convert a decimal
// to equivalent binary representation
static string DecimalToBinary(int n)
{
// Stores the binary representation
string binstr = "";
while (n > 0)
{
// Since ASCII value of
// '0', '1' are 48 and 49
binstr += (char)(n % 2 + 48);
n = n / 2;
}
// As the string is already reversed,
// no further reversal is required
return new string(binstr.ToArray());
}
// Function to convert the reversed binary
// representation to equivalent integer
static int ReversedBinaryDecimal(int N)
{
// Stores reversed binary
// representation of given decimal
string decimal_to_binar = DecimalToBinary(N);
// Stores equivalent decimal
// value of the binary representation
int binary_to_decimal = BinaryToDecimal(
decimal_to_binar);
// Return the resultant integer
return binary_to_decimal;
}
// Utility function to print the sorted array
static void PrintSortedArray(int[] arr, int size)
{
// Sort the array
Array.Sort(arr);
// Traverse the array
for (int i = 0; i < size; i++)
// Print the array elements
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Utility function to reverse the
// binary representations of all
// array elements and sort the modified array
static void ModifyArray(int[] arr, int size)
{
// Traverse the array
for (int i = 0; i < size; i++)
{
// Passing array elements to
// ReversedBinaryDecimal function
arr[i] = ReversedBinaryDecimal(arr[i]);
}
// Pass the array to
// the sorted array
PrintSortedArray(arr, size);
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 98, 43, 66, 83 };
int n = arr.Length;
ModifyArray(arr, n);
}
}
Time Complexity: O(NlogN)
Auxiliary Space: O(log2M), where M denotes the maximum element present in the array.
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
4 min read
Sorting Algorithms A Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read