Last active
March 15, 2026 18:02
-
-
Save adarsh-chakraborty/5a4c94fcfcca2d4aa165f1fccd4558be to your computer and use it in GitHub Desktop.
Some common sorting algorithms
This file contains hidden or 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
| 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