Skip to content

Instantly share code, notes, and snippets.

@fazeelanizam13
Last active May 10, 2022 05:55
Show Gist options
  • Save fazeelanizam13/b7aa61db20a0b0a2129b2bd47eef4b3c to your computer and use it in GitHub Desktop.
Save fazeelanizam13/b7aa61db20a0b0a2129b2bd47eef4b3c to your computer and use it in GitHub Desktop.
//test cases
let tests = [
{
input: 3,
result: 'Please input an array of integers.'
},
{
input: '[]',
result: 'Please input an array of integers.'
},
{
input: [],
result: 'Please input an array of integers.'
},
{
input: [3, 9, 5, 1, 8],
result: [1, 3, 5, 8, 9]
},
{
input: [3, -9, 5, 1, -8],
result: [-9, -8, 1, 3, 5]
},
{
input: [0, -9, 0, 1, -8],
result: [-9, -8, 0, 0, 1]
},
{
input: [0, -9, '0', 1, '-8'],
result: 'Please input an array of integers.'
},
]
// puts the array through a round of rearranging elements
function nextRound(input) {
let arrayCopy = input
for (let i = 0; i < arrayCopy.length - 1; i++) {
let firstNo = arrayCopy[i]
let secondNo = arrayCopy[i + 1]
// if current number > next number, swap each other
if (firstNo > secondNo) {
arrayCopy[i + 1] = firstNo
arrayCopy[i] = secondNo
}
// else, leave them be
}
// return arranged array
return arrayCopy
}
// checks if the array elements are in ascending order
function needAnotherRound(input) {
for (let i = 0; i < input.length - 1; i++) {
let firstNo = input[i]
let secondNo = input[i + 1]
// if current number > next number, return true
if (firstNo > secondNo) {
return true
// else move to next number in array
} else {
continue
}
}
}
// validate input array elements
function isIntegerArray (input) {
// if an array
if (Array.isArray(input)) {
// if empty array
if (input.length < 1) return false
// iterate through each element and return false if one of them happens to be not an integer
for (let i = 0; i < input.length; i++) {
if (Number.isInteger(input[i])) continue
else return false
}
return true
// if not an array
} else return false
}
function bubbleSort(input) {
if (isIntegerArray(input)) {
let sortedArray = input
while (1) {
if (needAnotherRound(sortedArray)) {
sortedArray = nextRound(sortedArray)
continue
} else {
return sortedArray
}
}
} else return 'Please input an array of integers.'
}
// test
for (let i = 0; i < tests.length; i++) {
let pass = false
let result = bubbleSort(tests[i].input)
let expectedResult = tests[i].result
if (JSON.stringify(result) === JSON.stringify(expectedResult)) pass = true
console.log(`input ${i} - ${pass ? 'pass' : 'fail'}`)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment