How to sort an array of integers correctly
By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
console.log(numArray);
How to sort integer array in ascending and descending order using lambda only in java
You could sort the input of type Integer[]
as :
Integer[] arr2 = new Integer[] {54,432,53,21,43};
Arrays.sort(arr2, Comparator.reverseOrder());
or possibly with primitive types as :
int[] arr2 = new int[]{54, 432, 53, 21, 43};
int[] sortedArray = Arrays.stream(arr2)
.boxed()
.sorted(Comparator.reverseOrder()) // just use 'sorted()' for ascending order
.mapToInt(Integer::intValue)
.toArray();
or further using a trick from one of the existing answers (do note that it should be cautiously used with boundary values though) :
int[] sortedArray = Arrays.stream(arr2)
.map(i -> -i).sorted().map(i -> -i) // just use 'sorted()' for ascending order
// Edit - use map(i -> ~i).sorted().map(i -> ~i) to be safe from the issue with Integer.MIN_VALUE
.toArray();
Edit: For an in-place ascending order sort, you just need to perform :
int[] arr2 = new int[]{54, 432, 53, 21, 43};
Arrays.sort(arr2);
sorting array of arrays in descending order using arrays.sort function is resulting in errors in java
As mentioned in comments, you are sorting by inner element, which is int[]
, so you need Comparator<int[]>
.
public class Solution {
public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
Arrays.sort(input, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o2[1], o1[1]);
}
});
System.out.println(Arrays.deepToString(input));
}
}
Note return Integer.compare(o2[1], o1[1]);
, second parameter is compared to first in order to achieve descending order.
You could also achieve same effect using lambda, to make it shorter and more readable.
public class Solution {
public static void main(String[] args) {
int[][] input = new int[][]{new int[]{2, 2}, new int[]{1, 3}, new int[]{3, 1}};
System.out.println("Initial array - " + Arrays.deepToString(input));
Arrays.sort(input, (o1, o2) -> Integer.compare(o2[1], o1[1]));
System.out.println("Sorted array - " + Arrays.deepToString(input));
}
}
Very fast way to sort array of integers?
I finally came with a simple and pretty elegant solution :
read N
for (( i=0; i<N; i++ )); do
read tab[i]
done
printf "%i\n" ${tab[@]} | sort -n | awk 'BEGIN{dmin=1000000;} (NR>1){d=$1-prec; if (d<dmin) dmin=d;} {prec=$1;} END{print dmin;}'
And that's it. :)
Thanks to all of you for taking the time to help me ! ;)
Sort an integer array, keeping first in place
You could save the value of the first element and use it in a condition for the first sorting delta. Then sort by the standard delta.
How it works (the sort order is from Edge)
condition numerical sortFn
a b delta delta result comment
----- ----- --------- --------- --------- -----------------
7 10* 1 1 different section
12* 7 -1 -1 different section
12* 10* 0 2 2 same section
12* 7 -1 -1 same section
3 7 0 -4 -4 same section
3 12* 1 1 different section
3 7 0 -4 -4 same section
5 7 0 -2 -2 same section
5 12* 1 1 different section
5 3 0 2 2 same section
5 7 0 -2 -2 same section
6 7 0 -1 -1 same section
6 3 0 3 3 same section
6 5 0 1 1 same section
6 7 0 -1 -1 same section
* denotes elements who should be in the first section
Elements of different section means one of the elements goes into the first and the other into the second section, the value is taken by the delta of the condition.
Elements of the same section means, both elements belongs to the same section. For sorting the delta of the values is returned.
function sort(array) {
var first = array[0];
array.sort(function (a, b) {
return (a < first) - (b < first) || a - b;
});
return array;
}
console.log(sort([10, 7, 12, 3, 5, 6]));
console.log(sort([12, 8, 5, 9, 6, 10]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Optimized and efficient way to sort int[] primitive array in Java
First off, you code has a few issues with the 2nd and 3rd line of the for loop, since the first index it tries to access is "6", which doesn't exist. The last line of the for loop has an extra ]
So, I think this is what you meant, feel free to correct me if I've got this wrong!
for(int i = 0; i <= arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
But if you want to maintain lower space complexity, I think the in-place modification you have is pretty close to as small as you're going to get. Even with streams, it's not going to get much shorter (but will get somewhat subjectively messier).
Also, not to complicate things further, but if your array uses a sufficiently small range (edit: and more importantly, you know that range beforehand), you can use counting sort, which is O(n+k) time complexity vs. Arrays.sort()
Array sorting in c by reference
You're going off the end of the array:
for (int i = 0 ; i < size ; i++){
if(array[i] > array[i+1]){
When i
is size-1
, array[i+1]
is one element past the end of the array. Reading or writing past the bounds of an array triggers undefined behavior, which in this case manifests as a 0
element showing up in the list.
Change your loop condition to:
for (int i = 0 ; i < size - 1 ; i++){
Sort Int array using lamda java 8
Arrays#sort
requires a Comparator
to sort the array. You can reverse the order of arguments to Comparator#compare
for the comparison to happen in the reverse order.
Without lambda, you would do it as
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
Arrays.sort(arr, new Comparator<Integer>() {
@Override
public int compare(Integer x, Integer y) {
return Integer.compare(y, x);
}
});
System.out.println(Arrays.toString(arr));
}
}
Output:
[100, 45, 21, 13, 9, 7, 6, 2]
Lambda helps you get rid of all the things enclosed by a rectangle in the picture given below:
The things enclosed by a green rectangle are not required when you have just one statement in the body.
Thus, using lambda, the code becomes:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
Arrays.sort(arr, (x, y) -> Integer.compare(y, x));
System.out.println(Arrays.toString(arr));
}
}
Output:
[100, 45, 21, 13, 9, 7, 6, 2]
Sorting an int array from highest to lowest
If you use an Integer[]
instead of int[]
, then you can pass a Comparator
as 2nd argument to the sort method. To impose reverse ordering, you can make use of Collections.reverseOrder()
method:
Arrays.sort(arr, Collections.reverseOrder());
Related Topics
Codable Decode Property with Multiple Object Types Based on Another Value
Use of or Operator on Cloudkit Predicate
Store Data in Custom Class Array in Core Data
Accessing and Manipulating Array Item in an Environmentobject
Node.Physicsbody.Joints Downcasting Error
Ordering Firebase Posts Chronologically Swift
How to Conditionally Define a Podspec Property Depending on Static or Dynamic Usage
Why Does Xcode Line-Out Autocomplete Methods for Selector
How to Execute Different Implementation of a Method of a Generic Struct Based on the Generic Type
Nsattributedstring and Emojis: Issue with Positions and Lengths
How to Integrate Mapbox Sdk with Swiftui
Swiftui Mysterious Spacing Between Large Text and Textfield in VStack
Nsurl Fail Able Initialiser Initwithstring: Does Not Return Nil on Empty String in Swift
How Is a Global Variable Set to Private Understood in Swift
How to Pass Arguments into a Function with Completion Swift
Get All Documents at Once in a Completion Handler with Getdocuments in Firestore