Created
May 23, 2022 13:25
-
-
Save jayantasamaddar/b4818ab28e280d214560571c122086b5 to your computer and use it in GitHub Desktop.
Implement a Bubble Sort Algorithm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Using C Style for-Loop */ | |
const bubbleSort = array => { | |
const arr = array.slice(); | |
for (let i = 0; i < arr.length - 1; i++) { | |
for (let j = 0; j < arr.length - 1 - i; j++) { | |
if (arr[j] > arr[j + 1]) { | |
swap(arr, j, j + 1); | |
} | |
} | |
} | |
return arr; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Using while-loop */ | |
const bubbleSort2 = array => { | |
const arr = array.slice(); | |
let counter = arr.length; | |
while (counter > 0) { | |
for (let i = 0; i < arr.length - 1; i++) { | |
if (arr[i] > arr[i + 1]) swap(arr, i, i + 1); | |
} | |
counter--; | |
} | |
return arr; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Using recursive Function */ | |
const bubbleSort3 = array => { | |
const arr = array.slice(); | |
const recursiveSort = (arr, indx) => { | |
let i = indx; | |
if (i === arr.length - 1) return arr; | |
for (let j = 0; j < arr.length - 1 - i; j++) { | |
if (arr[j] > arr[j + 1]) { | |
swap(arr, j, j + 1); | |
} | |
} | |
i++; | |
return recursiveSort(arr, i); | |
}; | |
return recursiveSort(arr, 0); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment