Skip to content

Instantly share code, notes, and snippets.

@sli
Last active November 12, 2018 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sli/fff248ee1035f71f107ae8afbb91233d to your computer and use it in GitHub Desktop.
Save sli/fff248ee1035f71f107ae8afbb91233d to your computer and use it in GitHub Desktop.
bubble sort
const makeCourse = (code, name) => ({ code, name })
const makeHonors = (course, section, semester) => ({ course, section, semester })
const courses = [
makeCourse(220, 'D Two Two Zero'),
makeCourse(110, 'A One One Zero'),
makeCourse(130, 'C One Three Zero'),
makeCourse(120, 'B One Two Zero')
]
const honors = courses
.map(c => makeHonors(c, c.name.split(' ')[0], 'Fall'))
const courseComparitor = (a, b) => a.code > b.code
const honorsComparitor = (a, b) => a.course.code > b.course.code
const sortAnything = (data, comparitor = (a, b) => a > b) => {
let sorted = false
while (!sorted) {
sorted = true
for (let i = 1; i < data.length; i++) {
if (comparitor(data[i-1], data[i])) {
sorted = false
temp = data[i]
data[i] = data[i-1]
data[i-1] = temp
}
}
}
return data
}
console.dir(courses)
console.log('-----')
console.dir(sortAnything(courses, courseComparitor))
console.log('\n\n')
console.dir(honors)
console.log('-----')
console.dir(sortAnything(honors, honorsComparitor))
const makeCourse = (code, name) => ({ code, name })
const makeHonors = (course, section, semester) => ({ course, section, semester })
const courses = [
makeCourse(220, 'D Two Two Zero'),
makeCourse(110, 'A One One Zero'),
makeCourse(130, 'C One Three Zero'),
makeCourse(120, 'B One Two Zero')
]
const honors = courses.map(c => makeHonors(c, c.name.split(' ')[0], 'Fall'))
const sortCourses = courses => {
let sorted = false
while (!sorted) {
sorted = true
for (let i = 1; i < courses.length; i++) {
if (courses[i-1].code > courses[i].code) {
sorted = false
temp = courses[i]
courses[i] = courses[i-1]
courses[i-1] = temp
}
}
}
return courses
}
const sortHonors = honors => {
let sorted = false
while (!sorted) {
sorted = true
for (let i = 1; i < honors.length; i++) {
if (honors[i-1].course.code > honors[i].course.code) {
sorted = false
temp = honors[i]
honors[i] = honors[i-1]
honors[i-1] = temp
}
}
}
return honors
}
console.dir(courses)
console.log('-----')
console.dir(sortCourses(courses))
console.log('\n\n')
console.dir(honors)
console.log('-----')
console.dir(sortHonors(honors))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment