Skip to content

Instantly share code, notes, and snippets.

@tiagoamaro
Last active August 23, 2022 05:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save tiagoamaro/b4035380d32b49b89705e094dd050b1f to your computer and use it in GitHub Desktop.
Save tiagoamaro/b4035380d32b49b89705e094dd050b1f to your computer and use it in GitHub Desktop.
Lógica de Programação 2020 - Aula 06
function bubbleSort (items) {
const length = items.length
for (let i = (length - 1); i >= 0; i--) {
for (let j = (length - i); j > 0; j--) {
// Compare the adjacent positions
if (items[j] < items[j - 1]) {
// Swap the numbers
const tmp = items[j]
items[j] = items[j - 1]
items[j - 1] = tmp
}
}
}
}
const collection = [3, 2, 6, 10]
collection.sort() // will return sorted array
collection // won't mutate the variable
function insertionSort (collection) {
const len = collection.length
for (let unsortedIndex = 1; unsortedIndex < len; unsortedIndex++) {
let sortedIndex = unsortedIndex
const element = collection[unsortedIndex]
while (sortedIndex > 0 && collection[sortedIndex - 1] > element) {
collection[sortedIndex] = collection[sortedIndex - 1]
sortedIndex--
}
collection[sortedIndex] = element
}
return collection
}
function quicksort (array) {
if (array.length <= 1) {
return array
}
const pivot = array[0]
const left = []
const right = []
for (let i = 1; i < array.length; i++) {
array[i] < pivot ? left.push(array[i]) : right.push(array[i])
}
return quicksort(left).concat(pivot, quicksort(right))
};
const collection = [5, 12, 8, 130, 44];
const found = collection.find(element => element === 12);
console.log(found) // will print 12
function linearSearch (value, list) {
let found = false
let position = -1
let index = 0
while (!found && index < list.length) {
if (list[index] === value) {
found = true
position = index
} else {
index += 1
}
}
return position
}
function binarySearch (collection, element) {
let start = 0
let end = collection.length - 1
while (start <= end) {
// Find the middle
const mid = Math.floor((start + end) / 2)
// Found the element!
if (collection[mid] === element) {
return true
} else if (collection[mid] < element) {
start = mid + 1
} else {
end = mid - 1
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment