1
1
console . log ( "-------------------------------------------------" ) ;
2
- console . log ( "Activity 1: " ) ;
2
+ console . log ( "Activity 1: " ) ;
3
+
4
+ // Task 1: Implement the bubble sort algorithm to sort an array of numbers in ascending order. Log the sorted array.
5
+
6
+ const bubbleSort = ( arr ) => {
7
+ let len = arr . length ;
8
+ let swapped ;
9
+ do {
10
+ swapped = false ;
11
+ for ( let i = 0 ; i < len ; i ++ ) {
12
+ if ( arr [ i ] > arr [ i + 1 ] ) {
13
+ let temp = arr [ i ] ;
14
+ arr [ i ] = arr [ i + 1 ] ;
15
+ arr [ i + 1 ] = temp ;
16
+ swapped = true ;
17
+ }
18
+ }
19
+ } while ( swapped ) ;
20
+ return arr ;
21
+ }
22
+
23
+ let arr = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ] ;
24
+ console . log ( "Bubble Sort: " , bubbleSort ( arr ) ) ;
25
+
26
+ // Task 2: Implement the selection sort algorithm to sort an array of numbers in ascending order. Log the sorted array.
27
+
28
+ const selectionSort = ( arr ) => {
29
+ let len = arr . length ;
30
+ for ( let i = 0 ; i < len ; i ++ ) {
31
+ let min = i ;
32
+ for ( let j = i + 1 ; j < len ; j ++ ) {
33
+ if ( arr [ j ] < arr [ min ] ) {
34
+ min = j ;
35
+ }
36
+ }
37
+ if ( min !== i ) {
38
+ let temp = arr [ i ] ;
39
+ arr [ i ] = arr [ min ] ;
40
+ arr [ min ] = temp ;
41
+ }
42
+ }
43
+ return arr ;
44
+ }
45
+
46
+ let arr2 = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ] ;
47
+ console . log ( "Selection Sort: " , selectionSort ( arr2 ) ) ;
48
+
49
+
50
+ // Task 3: Implement the quicksort algorithm to sort an array of numbers in ascending order. Log the sorted array.
51
+
52
+ const quickSort = ( arr ) => {
53
+ if ( arr . length <= 1 ) {
54
+ return arr ;
55
+ }
56
+
57
+ let pivot = arr [ 0 ] ;
58
+ let left = [ ] ;
59
+ let right = [ ] ;
60
+
61
+ for ( let i = 1 ; i < arr . length ; i ++ ) {
62
+ if ( arr [ i ] < pivot ) {
63
+ left . push ( arr [ i ] ) ;
64
+ } else {
65
+ right . push ( arr [ i ] ) ;
66
+ }
67
+ }
68
+
69
+ return quickSort ( left ) . concat ( pivot , quickSort ( right ) ) ;
70
+ }
71
+
72
+ let arr3 = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ] ;
73
+ console . log ( "Quick Sort: " , quickSort ( arr3 ) ) ;
74
+
75
+ console . log ( "-------------------------------------------------" ) ;
76
+ console . log ( "Activity 2: " ) ;
77
+
78
+ console . log ( "-------------------------------------------------" ) ;
79
+ console . log ( "Activity 3: " ) ;
80
+
81
+ console . log ( "-------------------------------------------------" ) ;
82
+ console . log ( "Activity 4: " ) ;
83
+
84
+ console . log ( "-------------------------------------------------" ) ;
85
+ console . log ( "Activity 5: " ) ;
0 commit comments