1
2
3
4
5 let numbers = [0, 1, 2, 3, 10, 20, 30];
6numbers.sort((a, b) => a - b);
7
8console.log(numbers);
1var names = ["Peter", "Emma", "Jack", "Mia", "Eric"];
2names.sort(); // ["Emma", "Eric", "Jack", "Mia", "Peter"]
3
4var objs = [
5 {name: "Peter", age: 35},
6 {name: "Emma", age: 21},
7 {name: "Jack", age: 53}
8];
9
10objs.sort(function(a, b) {
11 return a.age - b.age;
12}); // Sort by age (lowest first)
1arr = ['width', 'score', done', 'neither' ]
2arr.sort() // results to ["done", "neither", "score", "width"]
3
4arr.sort((a,b) => a.localeCompare(b))
5// if a-b (based on their unicode values) produces a negative value,
6// a comes before b, the reverse if positive, and as is if zero
7
8//When you sort an array with .sort(), it assumes that you are sorting strings
9//. When sorting numbers, the default behavior will not sort them properly.
10arr = [21, 7, 5.6, 102, 79]
11arr.sort((a, b) => a - b) // results to [5.6, 7, 21, 79, 102]
12// b - a will give you the reverse order of the sorted items
13
14//this explnation in not mine
1
2var fruits = ["Banana", "Orange", "Apple", "Mango"];
3
4fruits.sort();
5
1homes.sort(function(a, b) {
2 return parseFloat(a.price) - parseFloat(b.price);
3});
1def merge_sort(array, left_index, right_index):
2 if left_index >= right_index:
3 return
4
5 middle = (left_index + right_index)//2
6 merge_sort(array, left_index, middle)
7 merge_sort(array, middle + 1, right_index)
8 merge(array, left_index, right_index, middle)
9