DEV Community

raquelhn
raquelhn

Posted on

2

Understanding Sorting Algorithms - Javascript

QUICKSORT
The first step is to find a pivot, and once this is picked, the array is divided in 2 sub arrays, one of them with the values less than the pivot value and the other other with values more than the pivot value, and this would be sorted by using the quicksort algorithm recursively
It has a complexity of O(n log(n)) so it's more efficient than the others

function quickSort(arr){
//its important to have a base case when it's a recursion
if(arr<=1){
return arr
}
let pivot = arr[arr.length-1]
left=[]
right=[]
for(let i=0;i<arr.length-1;i++){
if(arr[i]<pivot){
left.push(arr[i])
}else{
right.push(arr[i])
}
}

return [...quickSort(left),pivot,...quickSort(right)]
}

SELECTION SORT
Selects the minimum value in the list and swaps it with the first element of the list, it continues to do this until the list is sorted.
The idea to implement this algorithm is to sort through the whole list, and in an inner loop sort to find the index of the min number, so once we have this we can swap this number with the first one of that inner loop.

It's important to mention that this is not the most efficient algorithm, since it has an O complexity of O(n^2)

function sortSel(arr){
for(let i=0;i<arr.length-1;i++){
let minIndex=i
for(let j=i+1;j<arr.length;j++){
//if the min num changes then the index updates
if(arr[j]<arr[minIndex]){
minIndex=j
}
}

temp=arr[i]
arr[i]=arr[minIndex]
arr[minIndex]=arr[i]
}

return arr

}

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay