sort array in ascending order code example
Example 1: sorting array from highest to lowest javascript
let numbers = [5, 13, 1, 44, 32, 15, 500]
let lowestToHighest = numbers.sort((a, b) => a - b);
let highestToLowest = numbers.sort((a, b) => b-a);
Example 2: sorting program in c
#include<stdio.h>
int main(){
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
scanf("%d",&number[i]);
for(i=0;i<count;i++){
for(j=i+1;j<count;j++){
if(number[i]>number[j]){
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
printf(" %d",number[i]);
return 0;
}
Example 3: string sort javascript
var names = ["Peter", "Emma", "Jack", "Mia"];
var sorted = names.sort();
Example 4: how to sort array least to greatest javascript stACK
function sortArray(array) {
var temp = 0;
for (var i = 0; i < array.length; i++) {
for (var j = i; j < array.length; j++) {
if (array[j] < array[i]) {
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
return array;
}
console.log(sortArray([3,1,2]));