简体   繁体   中英

Sort array on basis of Bit count in ascending order

Please tell me what changes shall i make to sort the array in ascending order, on count of bits Consider an array of n decimal integers named elements. We want to rearrange elements according to the following rules:

Sort the integers in ascending order by the number of 1's in their binary representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1 in binary) would be ordered before 7 (which has triple 1's in binary). Two or more integers having the same number of 1's in their binary representations are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both contain double 1's in their binary representation, so 5 would be ordered before 6 because it has the smaller decimal value.

Where am I wrong? Input: 5 5 3 7 10 14 Ouput: 3 5 10 7 14

Code:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Tester {

    /**
     * Complete the function below.
     * DONOT MODIFY anything outside this function!
     */
    static int[] rearrange(int[] elements) {
         int[] aux= new int[elements.length];
         int a;
        for (int i=0; i<elements.length; i++){
            int count = 0;

            a=elements[i];
             for(int k =0; k<32; k++){
            if( (a&1) == 1) { 
              count++; } 
              a = a >>> 1;
              } 

                aux[i]=count;
                System.out.println(aux[i]);
            //    System.out.println(elements[i]);
        }

       //System.out.println(aux);
        //System.out.println(elements);
        for (int i = 1; i < (elements.length); i++)
    {
                //System.out.println(aux[i]);
                //System.out.println(elements[i]);
        // use 2 keys because we need to sort both
        // arrays simultaneously
        int key1 = aux[i];
        int key2 = elements[i];
        int j = i-1;

        /* Move elements of arr[0..i-1] and aux[0..i-1],
           such that elements of aux[0..i-1] are
           greater than key1, to one position ahead
           of their current position */
        while (j >= 0 && aux[j] > key1)
        {
            aux[j+1] = aux[j];
            elements[j+1] = elements[j];
            j = j-1;
        }
        aux[j+1] = key1;
        elements[j+1] = key2;
        }
        //System.out.println(aux);
        return elements;
    }


    /**
     * DO NOT MODIFY THIS METHOD!
     */
    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(System.in);

        int n = 0;
        n = Integer.parseInt(in.nextLine().trim());
        int[] elements = new int[n];
        int element;
        for (int i = 0; i < n; i++) {
            element = Integer.parseInt(in.nextLine().trim());
            elements[i] = element;
        }

        // call rearrange function
        int[] results =rearrange(elements);

        for (int i = 0; i < results.length; i++) {
        System.out.println(String.valueOf(results[i]));
        }
    }
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/*
 * Sort the integers in ascending order by the number of 1's in their binary
 * representations. For example, 7→ 111 and 8 → 1000, so 8 (which has single 1
 * in binary) would be ordered before 7 (which has triple 1's in binary). Two or
 * more integers having the same number of 1's in their binary representations
 * are ordered by increasing decimal value. For example, 5 → 101 and 6→ 110 both
 * contain double 1's in their binary representation, so 5 would be ordered
 * before 6 because it has the smaller decimal value.
 */

public class Solution {

public static void main(String[] args) {
    List<Integer> myList = new ArrayList<>();
    myList.add(5);
    myList.add(3);
    myList.add(5);
    myList.add(7);
    myList.add(10);
    myList.add(14);
    myList.add(6);      

    Solution s1 = new Solution();
    System.out.println("before: " + myList.toString());
    /*
     * for (Integer num : myList) { System.out.println("*** sNumber = " + num);
     * System.out.println("Binary = " + Integer.toBinaryString(num));
     * System.out.println("Number of one bits = " + Integer.bitCount(num)); }
     */
    System.out.println("after: " + s1.rearrangeList(myList).toString());

}

public List<Integer> rearrangeList(List<Integer> theList) {

    Collections.sort(theList, new Comparator<Integer>() {

        @Override
        public int compare(Integer num1, Integer num2) {
            /*
             * a negative integer, zero, or a positive integer as the first argument 
             * is less
             * than, equal to, or greater than the second.
             */
            int result = 0;
            if (num1 == num2) {
                result = 0;
            } else if (Integer.bitCount(num1) < Integer.bitCount(num2)) {// 5=101 and 
                                                                         // 7=111
                result = -1;
            } else if (Integer.bitCount(num1) > Integer.bitCount(num2)) {// 7=111 and 
                                                                         // 6=110
                result = 1;
            } else if (Integer.bitCount(num1) == Integer.bitCount(num2)) {// 5=101 
                                                                          // 10=1010
                result = (num1 < num2) ? -1 : 1;// sort in natural order
            }
            return result;
        }
    });

    return theList;
    }

}
public static List<Integer> rearrange(List<Integer> elements){
    if(elements == null) {
        return null;
    }
    Collections.sort(elements, new sortByBinaryRep());
    Set<Integer> set = new LinkedHashSet<>(elements);
    return new LinkedList<>(set);
}

import java.util.Comparator;

public class sortByBinaryRep implements Comparator<Integer> {

    @Override
    public int compare(Integer num1, Integer num2) {
        String binaryRep1 = Integer.toBinaryString(num1);
        String binaryRep2 = Integer.toBinaryString(num2);
        int bits1 = countBits(binaryRep1);
        int bits2 = countBits(binaryRep2);

        if(bits1 == bits2) {
            return num1 - num2;
        }
        else {
            return bits1 - bits2;
        }
    }

    private int countBits(String a){
        int count = 0;
        for(char c: a.toCharArray()) {
            if(c == '1') {
                count++;
            }
        }
        return count;
    }
}

This is the C# code for anyone interested:

using System;

namespace ConsoleApp1
{
class Program
{
    static int[] rearrange(int[] elements)
    {
        Array.Sort(elements);

        int[] countOfOnesFromElements = new int[elements.Length];
        int currentElement;
        for (int i = 0; i < elements.Length; i++)
        {
            int countTheNumberOfOnes = 0;

            currentElement = elements[i];
            for (int k = 0; k < 32; k++)
            {
                if ((currentElement & 1) == 1)
                {
                    countTheNumberOfOnes++;
                }
                currentElement = currentElement >> 1;
            }

            countOfOnesFromElements[i] = countTheNumberOfOnes;
            Console.WriteLine(countOfOnesFromElements[i]);
        }
        for (int i = 1; i < (elements.Length); i++)
        {
            int key1 = countOfOnesFromElements[i];
            int key2 = elements[i];
            int j = i - 1;

            while (j >= 0 && countOfOnesFromElements[j] > key1)
            {
                countOfOnesFromElements[j + 1] = countOfOnesFromElements[j];
                elements[j + 1] = elements[j];
                j = j - 1;
            }
            countOfOnesFromElements[j + 1] = key1;
            elements[j + 1] = key2;
        }

        return elements;           
    }
    static void Main(string[] args)
    {
        int[] res;

        int _elements_size = 0;
        Console.WriteLine("Input the element size: ");
        _elements_size = Convert.ToInt32(Console.ReadLine());
        int[] _elements = new int[_elements_size];
        int _elements_item;

        for(int _elements_i = 0; _elements_i < _elements_size; _elements_i++)
        {
            Console.WriteLine("What is Element {0}? ", _elements_i);
            _elements_item = Convert.ToInt32(Console.ReadLine());
            _elements[_elements_i] = +_elements_item;
        }

        res = rearrange(_elements);
        Console.WriteLine("\r\nAll elements in order of binary");
        for(int res_i = 0; res_i < res.Length; res_i++)
        {
            Console.WriteLine(res[res_i]);               
        }
        Console.ReadLine();

    }
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM