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 58f6c7a

Browse files
author
Swastikyadav
committed
Implement bubbleSort and selectionSort algorithm
1 parent 59c5247 commit 58f6c7a

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

‎DsAlgo-Questions/27-bubbleSort.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
Sort a given array using bubbleSort.
3+
*/
4+
5+
function bubbleSort(array) {
6+
let isSwapped;
7+
8+
for(let i = array.length; i > 0; i--) {
9+
isSwapped = false;
10+
11+
for(let j = 0; j < i - 1; j++) {
12+
if(array[j] > array[j + 1]) {
13+
[array[j], array[j+1]] = [array[j+1], array[j]];
14+
isSwapped = true;
15+
}
16+
}
17+
18+
if(!isSwapped) {
19+
break;
20+
}
21+
}
22+
23+
return array;
24+
}
25+
26+
console.log(bubbleSort([6, 3, 5, 2]));
27+
28+
// In bubble sort algo, we swap the larger number to the end by comparing each number with the previous number, until the array is sorted.
29+
30+
/*
31+
Time Complexity of Bubble Sort Algorithm
32+
33+
There is a nested loop and both loop runs n times, so time complexity for this algo is (n * n) that is Quadratic Time Complexity O(n^2).
34+
*/

‎DsAlgo-Questions/28-selectionSort.js

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/*
2+
Sort the given array using selection sort.
3+
*/
4+
5+
function selectionSort(arr) {
6+
for (let i = 0; i < arr.length; i++) {
7+
let indexOfMin = i; // Assuming that i has the least value.
8+
9+
for (let j = i + 1; j < arr.length; j++) {
10+
if (arr[j] < arr[indexOfMin]) {
11+
indexOfMin = j;
12+
}
13+
}
14+
15+
if (indexOfMin !== 1) {
16+
[arr[i], arr[indexOfMin]] = [arr[indexOfMin], arr[i]];
17+
}
18+
}
19+
20+
return arr;
21+
}

0 commit comments

Comments
(0)

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