Skip to content

Commit 78773bc

Browse files
feat: Added Bubble sort (#56)
1 parent 1114140 commit 78773bc

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

Sorts/BubbleSort.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/**
2+
* @function bubbleSort
3+
* @description Bubble sort algorithm is simple and easy. In bubble sort every pair of adjacent value is compared and swap if the first value is greater than the second one. By this with every iteration the greatest value goes to the right side making it ascending order.This algorithm is not suitable for large data sets as its average and worst-case time complexity is quite high.
4+
* @Complexity_Analysis
5+
* Space complexity - O(1)
6+
* Time complexity 
7+
*      Best case   -   O(n^2)
8+
* The best case occurs when an array is already sorted.
9+
*      Worst case  -   O(n^2)
10+
* The worst case occurs when an array is reverse sorted.
11+
*      Average case -  O(n^2)
12+
* The average case occurs when an array is reverse sorted.
13+
*
14+
* @param {number[]} arr - The input array
15+
 * @return {number[]} - The sorted array.
16+
* @see [Bubble Sort](https://www.freecodecamp.org/news/bubble-sort)
17+
 * @example bubbleSort([8, 3, 5, 1, 4, 2]) = [1, 2, 3, 4, 5, 8]
18+
*/
19+
20+
export const bubbleSort = (arr: number[]): number[] => {
21+
22+
for (let i = 0; i < arr.length; i++) {
23+
for (let j = 0; j < arr.length-1; j++) { //iterating till the 2nd last element of array
24+
if (arr[j] > arr[j+1]) { //current indexed number > next indexed number
25+
let temp: number = arr[j]; //swapping two numbers
26+
arr[j] = arr[j+1];
27+
arr[j+1] = temp;
28+
}
29+
}
30+
}
31+
return arr;
32+
};

Sorts/test/BubbleSort.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import {bubbleSort} from "../BubbleSort"
2+
3+
describe("BubbleSort", () => {
4+
 it("should return the correct value for average case", () => {
5+
   expect(bubbleSort([8, 3, 5, 1, 4, 2])).toStrictEqual([1, 2, 3, 4, 5, 8]);
6+
 });
7+
8+
 it("should return the correct value for worst case", () => {
9+
    expect(bubbleSort([9, 8, 7, 6, 5, 4, 3, 2, 1])).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
10+
  });
11+
12+
 it("should return the correct value for best case", () => {
13+
   expect(bubbleSort([1, 2, 3, 4, 5, 8])).toStrictEqual([1, 2, 3, 4, 5, 8]);
14+
  });
15+
});

0 commit comments

Comments
 (0)