Skip to content

Instantly share code, notes, and snippets.

@adarsh-chakraborty
Last active March 15, 2026 18:02
Show Gist options
  • Select an option

  • Save adarsh-chakraborty/5a4c94fcfcca2d4aa165f1fccd4558be to your computer and use it in GitHub Desktop.

Select an option

Save adarsh-chakraborty/5a4c94fcfcca2d4aa165f1fccd4558be to your computer and use it in GitHub Desktop.
Some common sorting algorithms
const arr = [200, 1, 76, 13, 1231, 88, 13, 4, -2, 0, 11, 69];
function bubbleSort(arr){
let n = arr.length;
for(let i=0;i<n-1;i++){
for(let j=0;j<n-1-i;j++){
if(arr[j] > arr[j+1]){
// swap; put j into j+1
// put j+1 in j
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
function selectionSort(arr){
let n = arr.length;
for(let i=0;i<n-1;i++){
let minimum = i;
for(let j=i+1;j<n;j++){ // From i+1 to end of array
if(arr[j] < arr[minimum]){
// current element is smaller than minimum
// update the minimum index
minimum = j;
}
}
// swap i with minimum
if(minimum != i){
let temp = arr[minimum];
arr[minimum] = arr[i];
arr[i] = temp;
}
}
return arr;
}
let result = selectionSort([...arr]);
console.log("Before Sorting:");
console.log(arr);
console.log("After Sorting:");
console.log(result);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment