how to sort elements in array code example
Example 1: how the sort function works javascript
const unsorted = ['d', 'd', 'h', 'r', 'v', 'z', 'f', 'c', 'g'];
const sorted = unsorted.sort();
console.log(sorted);
const unsortedNums = [45, 56, 3, 3, 4, 6, 7, 45, 1];
const sortedNums = unsortedNums.sort((a, b) => {
return a - b;
});
console.log(sortedNums);
Example 2: sorting in js
var arr = [23, 34343, 1, 5, 90, 9]
var sortedArr = [];
arr.forEach(x => {
if (sortedArr.length == 0)
sortedArr.push(x)
else {
if (sortedArr[0] > x) sortedArr.unshift(x)
else if (sortedArr[sortedArr.length - 1] < x) sortedArr.push(x)
else sortedArr.splice(sortedArr.filter(y => y < x).length, 0, x)
}
})
console.log(sortedArr);
console.log(arr.sort((a,b)=>{
return a-b;
}));
Example 3: how to sort array
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
+" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" "
+ array[8]+" " + array[9] );
}