 # Sorting challenge - Bubble sort giving wrong output even though array is sorted

My solution is certainly sorting the array but it is not returning the actual sorted array. Instead it is return some array of whose source I can’t find. I am at a loss and spent good part of last three hours on this simple exercise.

Array is fine before I make my recursive call, but immediately after it is not. I have clearly commented the point in the script below

``````function bubbleSort(array) {
console.log(array);
let pos = 0;
let isLow = true;

function recurse (x) {
if (isLow === false) { return x; }
while (pos < x.length) {
if (x[pos] > x[pos+1]) {
let so1 = x.splice(pos, 1);
let so2 = x.splice(pos, 1);
let temp = x.splice(pos);
x = [...x, ...so2, ...so1, ...temp];
}
pos += 1;
}
console.log('pos', x);
isLow = false;

for (let t=0; t<x.length; t++) {
if (x[t] > x[t+1]) {
isLow = true;
break;
}
}

pos = 0;
//console.log('pre', x);
recurse(x);
//console.log('pos', x);
return x;
}

let res = recurse(array);
return res;
}

let temp = bubbleSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]);
console.log(temp);`````````

what are you doing with the value returned from `recurse`?

Gah!!! That simple. Damn!
Thank you. thank you thank you.