logo
down
shadow

Sort only even numbers in array and do not touch odds


Sort only even numbers in array and do not touch odds

By : user2185662
Date : November 22 2020, 04:01 AM
around this issue I would not try to create a Comparator like that. Seems more like hassle to achieve it. Instead you could split the array in odd and even numbers. Sort the even numbers and add the odd numbers to their previous position with ArrayList#add(index,number)
code :


Share : facebook icon twitter icon
Given an array consisting of even and odd numbers. Sort the array with even first and then odds. The order of numbers ca

Given an array consisting of even and odd numbers. Sort the array with even first and then odds. The order of numbers ca


By : pascu catalin
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You can do this in O(n) with a two-pass approach, so long as you're allowed to allocate a separate output buffer. On the first pass, detect and copy all even numbers. On the second pass, detect and copy all odd numbers.
Trouble sorting an array of numbers into evens and odds

Trouble sorting an array of numbers into evens and odds


By : user2905802
Date : March 29 2020, 07:55 AM
like below fixes the issue I'm just learning JavaScript and am working on a problem where I sort an array of numbers into odd and even arrays.
code :
for (var i = 0; i < arguments.length; i++) {
                    ^^^^^^^^^^^^^^^^
for (var i = 0; i < nums.length; i++) {
Is there a way to more elegantly sort an array into even and odds?

Is there a way to more elegantly sort an array into even and odds?


By : harsha
Date : March 29 2020, 07:55 AM
I hope this helps you . Just a follow-up to my comment. Here is how you can do it in O(n) without extra-space:
code :
public class Main {
    public static void main(String[] args) {
        evenOdd(new int[]{1, 2, 3, 4, 5, 6, 7});
        evenOdd(new int[]{2, 3, 4, 5, 6, 7});
        evenOdd(new int[]{1, 1, 1, 1, 1});
        evenOdd(new int[]{2, 2, 2, 2});
    }

    public static void evenOdd(int[] a) {
        int firstOdd = 0;
        for (int i = 0; i < a.length; ++i) {
            if (a[i] % 2 == 0) {
                int t = a[firstOdd];
                a[firstOdd] = a[i];
                a[i] = t;
                firstOdd++;
//            } else {
//                else is redundant, just leave odd in-place
            }
        }
        System.out.println(Arrays.toString(a));
    }
}
Sort array of objects with dots, letters, numbers. I was able to sort by numbers, but mixed values are difficult. Not su

Sort array of objects with dots, letters, numbers. I was able to sort by numbers, but mixed values are difficult. Not su


By : Kobaissi
Date : March 29 2020, 07:55 AM
I hope this helps . You could split the string and use sorting with map, while comparing each element of the one with each element of the other one. if both elements are numbers, take the difference, otherwise return the result of localeCompare.
Bonus: Sort with roman numbers.
code :
function customSort(data, key, order) {

    function isNumber(v) {
        return (+v).toString() === v;
    }

    function isRoman(s) {
        // http://stackoverflow.com/a/267405/1447675
        return /^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/i.test(s);
    }

    function parseRoman(s) {
        var val = { M: 1000, D: 500, C: 100, L: 50, X: 10, V: 5, I: 1 };
        return s.toUpperCase().split('').reduce(function (r, a, i, aa) {
            return val[a] < val[aa[i + 1]] ? r - val[a] : r + val[a];
        }, 0);
    }

    var sort = {
            asc: function (a, b) {
                var i = 0,
                    l = Math.min(a.value.length, b.value.length);

                while (i < l && a.value[i] === b.value[i]) {
                    i++;
                }
                if (i === l) {
                    return a.value.length - b.value.length;
                }
                if (isNumber(a.value[i]) && isNumber(b.value[i])) {
                    return a.value[i] - b.value[i];
                }
                if (isRoman(a.value[i]) && isRoman(b.value[i])) {
                    return parseRoman(a.value[i]) - parseRoman(b.value[i]);
                }
                return a.value[i].localeCompare(b.value[i]);
            },
            desc: function (a, b) {
                return sort.asc(b, a);
            }
        },
        mapped = data.map(function (el, i) {
            var string = el[key].replace(/\d(?=[a-z])|[a-z](?=\.)/gi, '$&. .'),
                regex = /(\d+)|([^0-9.]+)/g,
                m,
                parts = [];

            while ((m = regex.exec(string)) !== null) {
                parts.push(m[0]);
            }
            return { index: i, value: parts, o: el, string: string };
        });

    mapped.sort(sort[order] || sort.asc);
    return mapped.map(function (el) {
        return data[el.index];
    });
}

var arr = [{ section: '12.2.a' }, { section: '12.2.b.viii' }, { section: '12.2.b.xi' }, { section: '12.2.b.x' }, { section: '12.2.b.ix' }, { section: '12.2.b.vii' }, { section: '12.2.b.vi' }, { section: '12.2.b.iv' }, { section: '12.2.b.v' }, { section: '12.2.b.ii' }, { section: '12.2.b.iii' }, { section: '12.2.b.i' }, { section: '12.2.b.iii' }, { section: '12.2.c' }, { section: '12' }, { section: '12A' }, { section: '12.3.b' }, { section: '12.3.c' }, { section: 'Q2' }, { section: 'Q32' }, { section: 'Q6' }, { section: 'Q5' }, { section: 'Q.10' }, { section: 'Q.1' }, { section: 'Q.2' }];

console.log('sorted array asc', customSort(arr, 'section'));
console.log('sorted array desc', customSort(arr, 'section', 'desc'));
console.log('original array', arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
How to get even numbers array to print first instead of odds?

How to get even numbers array to print first instead of odds?


By : Khanh Nguyễn
Date : March 29 2020, 07:55 AM
hop of those help? If you want to split the number by their even and odd values, instead of using the index (i), determine the sub array to push into using the value - numbersArray[i] % 2.
code :
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];

function divider(numbersArray) {
  var evensOdds = [[], []];
  for (var i = 0; i < numbersArray.length; i++) {
    evensOdds[numbersArray[i] % 2].push(numbersArray[i]);
  }
  return evensOdds;
}

console.log(divider(numbersArray));
var numbersArray = [1,2,34,54,55,34,32,11,19,17,54,66,13];

function divider(numbersArray) {
  var evensOdds = [[], []];
  for (var i = 0; i < numbersArray.length; i++) {
    evensOdds[(i + 1) % 2].push(numbersArray[i]);
  }
  return evensOdds;
}

console.log(divider(numbersArray));
Related Posts Related Posts :
  • Mutable fields should not be "public static"
  • How to remove fragment from URI
  • Add a node in xml using java only if the node has an attribute
  • java streams: elegant way to filter according an exception is thrown
  • Exception in thread, java code wont execute properly. If/else statments
  • using the same UI instance inside access method
  • Single Linked List in reverse order Java
  • Is there a java api that will identify the ipv6 address fd00:: as local/private?
  • Clear a cache with JSR-107 annotations
  • Store data from an array for later comparison
  • Why BufferedWriter here is not writing to the file even though I close it in the end?
  • Three methods to search: name; name and surname; and age in an array
  • When do I have to create new instance while using @Autowired
  • ArrayList public constructor - "Constructs an empty list with an initial capacity of ten" - where?
  • How to make assignable, number-like class in Java?
  • How to make a query in Firebase similar to a SQL query?
  • How to inflate SupportActionBar menu from outside Activity
  • Is it good practice using two navigation (component architecture) in the same app?
  • Can a method annotation handle errors thrown by this method?
  • How does the javadoc know which method each documentation comment is for?
  • Refactoring/moving java package between intellij projects
  • Why lists pksc11-tool seven Objects but Java Keystore has Only one
  • How to update an entity with an element-collection of type Map<String,String>?
  • How to solve a "1 producer 2 consumers" problem in java
  • java selenium - Nav to a page number not shown on a Paginated Table
  • Add dependecies to runtime image with Gradle
  • How to reload application.properties in runtime which is not part of jar
  • How to stream, in java, over a key->collection map, where each streamed element is the key and every element in the c
  • Android Listview - Load each row on thread
  • Vaadin: value from DateField is null after conversion
  • Payara 5 compatibility with Java 9
  • Deleting an item from RecyclerView + SQLite
  • Calling a function when an activity is returned to from fragment
  • Functions with different signatures, but the same body
  • How to check which installed JDK used during Gradle build process
  • Creating a reusable class
  • What does static in front of nested interface mean?
  • ByteBuffer Missing Data When decoded As string
  • How to remove Handler from adapter
  • Simple Todo android app with mlab dont add or edit
  • Type inference seems to fail vavr's Try works on jOOQ's fetchOne() function
  • Google Dataflow "No filesystem found for scheme gs"
  • Sort file based on date in file name
  • Accessing the position of the elements of an Enum
  • Best approach to having multiple DatagramChannels working on one port
  • Renaming hibernate envers id and timestamp columns
  • How can i find the smallest number in array while getting the element number
  • Showing Stage/Dialog more than once in javafx application that is launched by Platform.startup()
  • How to split strings and store into a hashmap of strings in java
  • Using mockito to test bigger services in Spring
  • Variable set with some value in the one cucumber step implementation is losing its value in the next step
  • How to keep track of users in React?
  • Reading from a file and storing the first Integer as a String and the rest as Integers
  • Getting error in firebase code android How to resolve?
  • How to represent non-java file in UML diagram?
  • How do I convert this JSON file from POJO and vice versa
  • How to get locator path printed
  • Argument is not assignable to 'int'
  • Saving Image Data in a "PNG" File in Java
  • Convert ArrayList(Hashmap<String,String>) to some Arraylists
  • shadow
    Privacy Policy - Terms - Contact Us © bighow.org