Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7e9c137

Browse files
Create sortinginjs
1 parent f56cfad commit 7e9c137

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

‎sortinginjs‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /