How to sort an array and have elements that start with digit first?

python sort by first digit
sorting based on number of digits
java program to arrange the digits of a number in ascending order
rearrange array elements so as to form two number such that their sum is maximum
array sorting in python
how to get the first digit of a number in java
sort numbers based on digits starting from most significant numbers
python sorted not working

How can I sort this array


so the result is


You could use PHP's built-in array operations and such to do a lot of the heavy lifting for you, thus cutting out a lot of the apparent complexity:

$names = preg_grep('/^\D/', $arr);
$versions = preg_grep('/^\d/', $arr);

usort($versions, 'version_compare');
usort($names, 'strcasecmp');

$sorted = array_merge(array_reverse($versions), $names);

Arrange array elements such that last digit of an element is equal to , Arrange array elements such that last digit of an element is equal to Recommended: Please try your approach on {IDE} first, before moving on to the solution. then we have traversed the euler path If the euler path starts. Approach: The idea is to store each element with its sum of digits in a vector pair and then sort all the elements of the vector according to the digit sums stored. Finally, print the elements in order.

You should use the usort function.

$isVersion = function($a) { return is_numeric( str_replace('.', '', $a) ); };
$sortFunction = function($a, $b) use($isVersion) { 
    if( $isVersion($a) && $isVersion($b) ) { 
        return version_compare($b, $a); // reversed for your proper ordering
    } elseif( $isVersion($a) ) { 
        return -1;
    } elseif( $isVersion($b) ) { 
        return 1;
    } else { 
        return strcasecmp($a, $b);

usort($yourArray, $sortFunction);

The usort function lets you use your own custom comparison callback. I wrote one here for you with the logic you desired: if both comparable items are versions, it uses version_compare to compare them with the parameters reversed since you want descending order. If the second comparable item is a string and the first is a version, the version is said to be "lower" than the string, and vice-versa. If both items are strings, it uses the strcasecmp comparison function to determine the proper ordering. Example in use: codepad

Sort the numbers according to their sum of digits, Given an array arr[] of N non-negative integers, the task is to sort these Recommended: Please try your approach on {IDE} first, before Approach: The idea is to store each element with its sum of digits in a sort(vp.begin(), vp.end()) ; Get hold of all the important DSA concepts with the DSA Self Paced� sort() method is a java.util.Arrays class method. Syntax: public static void sort(int[] arr, int from_Index, int to_Index) arr - the array to be sorted from_Index - the index of the first element, inclusive, to be sorted to_Index - the index of the last element, exclusive, to be sorted This method doesn't return any value.

It can be done with some array functions and a couple of loops.


$arr = array("4.0.1", "trunk", "branch", "4.1.0", "4.0.3", "1.2", "1.31", "1.10", "1.4.5");
$count = count($arr);
$alpha = array();
$new_arr = array();
for($i = 0; $i < $count; $i++) {
    if(!is_numeric(str_replace('.', '', $arr[$i]))) {
        $alpha[] = $arr[$i];
    } else {
        $new_arr[] = $arr[$i];
    $arr[$i] = null;
$new_arr = array_merge($new_arr, $alpha);

Demo here.

JavaScript Array sort: Sorting Array Elements, Therefore, to sort employees by hire date, you first have to create a valid Date object from the date string, and then compare two dates, which is the same as� Given an array of size n, arrange the first k elements of the array in ascending order and the remaining n-k elements in descending order. Examples: Input: arr[] = {5, 4, 6, 2, 1, 3, 8, 9, -1}, k = 4 Output: 2 4 5 6 9 8 3 1 -1. Input: arr[] = {5, 4, 6}, k = 2 Output: 4 5 6

You merely need to invert the version_compare() evaluation.

Code: (Demo)

$array = ["4.0.1", "trunk", "branch", "4.1.0", "4.0.3"];

usort($array, function($a, $b) {
    return version_compare($b, $a);



array (
  0 => '4.1.0',
  1 => '4.0.3',
  2 => '4.0.1',
  3 => 'branch',
  4 => 'trunk',

From PHP7.4, arrow function syntax can be used. (Demo)

usort($array, fn($a, $b) => version_compare($b, $a));

[PDF] Radix sort: least significant digit first, For example, we use radix 10 and sort the array to the right. We have writ- ten in leading 0's to make all elements three digits long. Stably sorting the ar-. cant digit, then on its second least significant digit, and so on up to its most significant digit. For example, we use radix 10 and sort the array to the right. We have writ-ten in leading 0’s to make all elements three digits long. Stably sorting the ar-ray on the least significant digit produces the second array. Stably sorting the second

Using JavaScript's sort Method for Sorting Arrays of Numbers , It can be tricky at first to understand the rules for the array sort method in JavaScript. Javascript arrays can contain different types of elements - strings, valueOf() method returns numeric values (such as the Date object). These input are the elements of the array. 4. Now, create a nested for loop with i and j as iterators. 5. Start the sorting in ascending order by extracting each element at position i of outer loop. 6. This element is being compared to every element from position i+1 to size-1 (means all elements present below this extracted element) 7.

How to sort an array numerically in JavaScript, Ever try to sort an array of integers in JavaScript using .sort() and get a weird result, where the order was not numeric? The array got sorted in� Check if an array is Wave Array; Add elements in start to sort the array | Variation of Stalin Sort; Program to sort an array of strings using Selection Sort; Bucket Sort To Sort an Array with Negative Numbers; Sort an Array which contain 1 to N values in O(N) using Cycle Sort; Sort an array where a subarray of a sorted array is in reverse order

[PDF] Digit-based sorting and data structures, To start, say we have n objects to sort whose keys are all integers in a small Make an array A of size r, of “buckets” (perhaps implemented as linked lists). Most-significant-first radix sort begins by sorting keys into buckets according to their bucket that has more than one element using the same procedure (sorting into� Arrange array elements such that last digit of an element is equal to first digit of the next element Given an array arr[] of integers, the task is to arrange the array elements such that the last digit of an element is equal to first digit of the next element.

  • Just a note: In the case where $a and/or $b are not version numbers, a lexical sort (like strcasecmp) will already put them in the right order (number first, then name). Seems to me you could get rid of the middle two cases.
  • Looks like this only works on >= PHP 5.3.0, 5.2.* throws an error.
  • @Shaquin: Yeah...closures were introduced in 5.3. If you're still using 5.2, you need to update anyway. :) But you can accomplish a similar result using create_function and/or regular old named functions.
  • What I mean is most online PHP interpreters that measure time and memory run PHP 5.2. I've edited my post to include a speed/memory comparison.
  • @Shaquin: And most servers, where you actually care about time and memory usage, run 5.3. :) The online interpreters still running 5.2 need to update.
  • Believe he wants the numeric part descending and the alpha part ascending, otherwise cool demo.
  • @shaunhusain It does sort the array in the order that he wants, though..?
  • No notice he wants 4.1.0 to appear first not last in the numeric list, I believe the basic issue is that he wants a mix of an ascending and a descending sort with regard to the ASCII characters, basically the only thing I can think of is to split the array into two arrays sort each separately then re-combine, but I'm unfamiliar with the solution provided below. Your answer I believe suffers from the same issue as the natcasesort solution. After reading through the usort solution it seems correct.
  • huh interesting I wonder why using a compare function wouldn't end up being faster unless it has to do with the number of conditions being checked (memory usage is understandable if pointers are simply being moved around rather than values being copied). If I was the OP or could +1 you again I would
  • @Shaquin: The speed difference seems due to the use of print_r rather than var_dump. See my ideone edit with only that changed (and the function name fixed).