Skip to content
This repository was archived by the owner on Jun 2, 2024. It is now read-only.

Commit 5e2086b

Browse files
authored
feat: add counting sort algo (#934)
1 parent 041268f commit 5e2086b

File tree

2 files changed

+53
-25
lines changed

2 files changed

+53
-25
lines changed
Lines changed: 25 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,25 @@
1-
function bubbleSort(arr){
2-
for(var i = 0; i < arr.length; i++){
3-
// Last i elements are already in place
4-
for(var j = 0; j < ( arr.length - i -1 ); j++){
5-
6-
// Checking if the item at present iteration
7-
// is greater than the next iteration
8-
if(arr[j] > arr[j+1]){
9-
10-
// If the condition is true then swap them
11-
var temp = arr[j]
12-
arr[j] = arr[j + 1]
13-
arr[j+1] = temp
14-
}
15-
}
16-
}
17-
// Print the sorted array
18-
console.log(arr);
19-
}
20-
21-
// Unsorted array
22-
var arr = [234, 43, 55, 63, 5, 6, 235, 547];
23-
24-
// Now pass this array to the bubbleSort() function
25-
bubbleSort(arr);
1+
function bubbleSort(arr){
2+
for(var i = 0; i < arr.length; i++){
3+
// Last i elements are already in place
4+
for(var j = 0; j < ( arr.length - i -1 ); j++){
5+
6+
// Checking if the item at present iteration
7+
// is greater than the next iteration
8+
if(arr[j] > arr[j+1]){
9+
10+
// If the condition is true then swap them
11+
var temp = arr[j]
12+
arr[j] = arr[j + 1]
13+
arr[j+1] = temp
14+
}
15+
}
16+
}
17+
// Print the sorted array
18+
console.log(arr);
19+
}
20+
21+
// Unsorted array
22+
var arr = [234, 43, 55, 63, 5, 6, 235, 547];
23+
24+
// Now pass this array to the bubbleSort() function
25+
bubbleSort(arr);

Javascript/Algorithms/slow-sort.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
function slowSort(arr) {
2+
/**
3+
* If the array has 1 or no elements then it is already sorted,
4+
* return the array.
5+
* Otherwise slice the array into two halves and merge sort each half,
6+
* then merge the two sorted halves.
7+
*/
8+
if (arr.length <= 1) {
9+
return arr;
10+
} else {
11+
const mid = Math.floor(arr.length / 2);
12+
const firstHalf = slowSort(arr.slice(0, mid));
13+
const secondHalf = slowSort(arr.slice(mid));
14+
15+
if (secondHalf[0] < firstHalf[firstHalf.length - 1]) {
16+
[firstHalf[mid - 1], secondHalf[0]] = [secondHalf[0], firstHalf[mid - 1]];
17+
}
18+
19+
return firstHalf.concat(secondHalf);
20+
}
21+
}
22+
23+
24+
// Example usage:
25+
const array = [9, 5, 2, 8, 3, 1, 4, 7, 6];
26+
const sortedArray = slowSort(array);
27+
console.log(sortedArray);
28+
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]

0 commit comments

Comments
 (0)