|
| 1 | +// Example array of numbers to be sorted |
| 2 | +let numbers = [4, 2, 8, 1, 6, 3, 7]; |
| 3 | + |
| 4 | +// Sorting the array in ascending order |
| 5 | +numbers.sort(function (a, b) { |
| 6 | + return a - b; |
| 7 | +}); |
| 8 | + |
| 9 | +console.log("Sorted in ascending order: " + numbers); |
| 10 | + |
| 11 | +// Sorting the array in descending order |
| 12 | +numbers.sort(function (a, b) { |
| 13 | + return b - a; |
| 14 | +}); |
| 15 | + |
| 16 | +console.log("Sorted in descending order: " + numbers); |
| 17 | + |
| 18 | +//custom sorting algorithm (quicksort) in JavaScript: |
| 19 | +function quickSort(arr) { |
| 20 | + if (arr.length <= 1) { |
| 21 | + return arr; |
| 22 | + } |
| 23 | + |
| 24 | + const pivot = arr[0]; |
| 25 | + const left = []; |
| 26 | + const right = []; |
| 27 | + |
| 28 | + for (let i = 1; i < arr.length; i++) { |
| 29 | + if (arr[i] < pivot) { |
| 30 | + left.push(arr[i]); |
| 31 | + } else { |
| 32 | + right.push(arr[i]); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + return quickSort(left).concat(pivot, quickSort(right)); |
| 37 | +} |
| 38 | + |
| 39 | +let numbers = [4, 2, 8, 1, 6, 3, 7]; |
| 40 | +let sortedNumbers = quickSort(numbers); |
| 41 | +console.log("Sorted with quicksort: " + sortedNumbers); |
0 commit comments