Bubble Sort

I want to write a function which sorts the elements of an array from lowest to highest. This is the code so far:

function bubble(num){
for (var i=0;i<num.lenght;i++){
for (var j=0;j<num.lenght-(i+1);j++){
if (num[j]>num[j+1]){
var z=num[j];
num[j]=num[j+1];
num[j+1]=z;
}
}
}
return num;}

When ever I give the function a list, it always returns the list, unsorted. I am confused as to what my mistake is. Please provide guidance.

There is a built in function for this the, sort:
For sorting numbers use:

bubbles.sort(function(a, b){return a - b}); // ascending order
bubbles.sort(function(a, b){return b - a}); // descending order

But you can simply use the function, note that this would only compare to numbers:

function bubbles(a, b) {
  return a - b;
}

You can read more about the sort method on the MDN web docs

Hope this helps :grinning:

Thank you for providing this information.

However, I’m moreso interested in where exactly my code is wrong- I’m very confused as to why.

1 Like

I keep testing your code and it keeps giving correct results? I’m creating an empty array and pushing 20 random numbers into it and using it as the input parameter. Each time it sorts the numbers correctly.

function bubble(num){
	for(var i=0; i<num.length; i++){
		for(var j=0;j<num.length-(i+1);j++){
			if(num[j]>num[j+1]){
				var z = num[j];
				num[j] = num[j+1];
				num[j+1] = z;
			}
		}
	}
	return num;
}

data = []
for(var i = 0; i < 20; i++){
	data.push(Math.floor(Math.random()*100))
}
console.log('unsorted:');
console.log(data);
console.log('sorted');
console.log(bubble(data));

Here the result on one test I ran:
unsorted:
[ 20, 26, 46, 14, 57, 11, 75, 31, 4, 51, 88, 1, 77, 20, 46, 25, 18, 98, 35, 45 ]
sorted
[ 1, 4, 11, 14, 18, 20, 20, 25, 26, 31, 35, 45, 46, 46, 51, 57, 75, 77, 88, 98 ]
[Finished in 0.1s]

1 Like

I really am very confused, maybe it has to do with the way the browser reads the code.

When I copy and paste your function (which differs from mine only in that the whitespace is formatted differently) into the text editor I use (VSCode), it works perfectly. But if I return back to the function I typed out, then the issue of returning the unsorted list arises again. I can’t really think of a reasonable explanation.

Thank you none the less- it’s reassuring to know that it supposedly works.

2 Likes

Yes, it definitely has to do with the formatting. I copied your code this time exactly as you posted and it just returned the original unsorted array. FYI im using Sublime Text 3, so now we know both our editors require proper formatting.

unsorted:
[ 4, 43, 56, 23, 57, 56, 34, 0, 17, 29, 1, 74, 16, 65, 90, 71, 36, 19, 35, 7 ]
sorted
[ 4, 43, 56, 23, 57, 56, 34, 0, 17, 29, 1, 74, 16, 65, 90, 71, 36, 19, 35, 7 ]
[Finished in 0.1s]
1 Like

Thank you, coming from other programming languages, I had assume JS to be whitespace agnostic. I will be more vigilant with regards to the formatting of my code in future.

1 Like

You probably saw by now that the only problem was the misspelling of lenght.

Here is another version refactored from your code…

const bubble = obj => {
  let t;
  for (let i = 0; i < obj.length; i++) {
    for (let j = obj.length - 1; j > i; j--) {
      if (obj[i] > obj[j]) {
        t = obj[i];
        obj[i] = obj[j];
        obj[j] = t;
      }
    }
  }
  return obj;
}
console.log(bubble([20, 26, 46, 14, 57, 11, 75, 31, 4, 51, 88, 1, 77, 20, 46, 25, 18, 98, 35, 45]))
// [ 1, 4, 11, 14, 18, 20, 20, 25, 26, 31, 35, 45, 46, 46, 51, 57, 75, 77, 88, 98 ]
console.log(bubble('threeblindmice'.split('')))
// [ 'b', 'c', 'd', 'e', 'e', 'e', 'h', 'i', 'i', 'l', 'm', 'n', 'r', 't' ]

It works pretty much the same way, finding the smallest value and putting it at the front of the slice while the slice gets progressively shorter. The only difference is how j iterates… from right to left down to but not including i.

2 Likes

Haha, yes your right. That was indeed the real problem, not the formatting. I retested the original code with the correct spelling and it worked fine! Thanks for pointing that out mtf.

2 Likes
const reverseRange = n => {
  let a = [];
  let i = 0;
  while (a.length < n) {
    a.push(n - i++);
  }
  return a;
}
const bubbleSort = obj => {
  let t;
  let r = reverseRange(obj.length)
  for (let i = 0; i < obj.length; i++) {
    r.pop();
    for (let j of r) {
      if (obj[i] > obj[j]) {
        t = obj[i];
        obj[i] = obj[j];
        obj[j] = t;
      }
    }
  }
  return obj;
}
console.log(bubbleSort('threeblindmice'.split('')));
// [ 'b', 'c', 'd', 'e', 'e', 'e', 'h', 'i', 'l', 'i', 'm', 'n', 'r', 't' ]
1 Like

Oddly enough, bubble sort is sometimes discounted as being the slowest or least efficient of sorting methods. That is not the case, though. When sample sizes are sufficiently small, say a few hundred, it actually holds its own. We wouldn’t be learning it if it had no value. It does have value when the sample is small. More refined sort methods only reveal their efficiency on large samples. Small samples actually weigh them down.

The language supports sorting and likely uses a pretty fast sort algorithm, likely in C, so pretty fast is heartily under rating it. That doesn’t mean we should avoid creating sort algorithms of our own. This is at the heart of programming and should not be bypassed because the tools are already present. Tools that somebody else created don’t help to teach us. They only make our job easier. Learning is not a job. Set the tools aside and create one’s own. They just may succeed at replacing existing tools one day.

2 Likes

Yes, I often hear it’s not efficient but like you mentioned for smaller sample sizes it works just fine. Also I think it is a rewarding training exercise for programmers to learn in the early stages.

2 Likes