Javascript - bubble sort does not work

Hello experts,

1.

Why after sorting "sortPrices" array, the "prices" array sorts too?

2.

Why the sorting doesn't work?
function sortPrices(prices) {
  
  var sortPrices = prices;
  //bubble sort
  for (i=0; i < sortPrices.length; i++) {
    for (j=0; j < sortPrices.length -i; j++) {
      if (sortPrices[j] > sortPrices[j+1]) {
        var temp = sortPrices[j];
        sortPrices[j] = sortPrices[j+1];
        sortPrices[j+1] = temp;
      }
    }
  }
  for (i=0; i < sortPrices.length; i++) {
    $(".after-sale").append("<p>" + sortPrices[i] + "</p>");
  }
}

Open in new window


* Codepen here - http://goo.gl/onrJ1Y
** Add some prices then click 1+1 sale button...the goal is to sort them => pair them => discount equal or lower price in each pair
LVL 1
Fajer39Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Alexandre SimõesManager / Technology SpecialistCommented:
Looks good to me.
I just changed your append loop because you should never do an append inside a loop.
Depending on the amount of items, this can cause some serious performance issues.
Apart from that, the sortPrices array is always properly sorted at the end.
$(function() {
  var prices = [];
  //mark is clicked
  $("#mark").on("click", function(e) {
    e.preventDefault;
    //store the entered price
    var price = $("#price").val();
    
    if (price >= 1) {
       prices.push(price);
      $("#price").val("");
    }
    else {
      alert("price must be at least 1 unit");
      return;
    }
    calculatePrices(prices);
  })
  
  $("#sale").on("click", function(e) {
    e.preventDefault;
    $(".after-sale > p").remove();
    sortPrices(prices);
   // calculateSale(prices);
  });
  
});

function calculatePrices(prices) {
  addPrices(prices);
}

function addPrices(prices) {
    var total = 0;
    $(".before-sale").prepend("<p>" + "item#" + prices.length +
                             " = " + prices[prices.length - 1] + "</p>");
    for(i=0; i < prices.length; i++) {
      total += prices[i]*1;
    }
    
    $(".total").html("total: " + total);
}

function sortPrices(prices) {
  var sortPrices = prices;

  //bubble sort
  for (i=0; i < sortPrices.length; i++) {
    for (j=0; j < sortPrices.length -i; j++) {
      if (sortPrices[j] > sortPrices[j+1]) {
        var temp = sortPrices[j];
        sortPrices[j] = sortPrices[j+1];
        sortPrices[j+1] = temp;
      }
    }
  }

  var pPrices = [];
  for (i=0; i < sortPrices.length; i++) {
    pPrices.push("<p>" + sortPrices[i] + "</p>");
  }
  $(".after-sale").append(pPrices.join(''));
}

function calculateSale() {
  //
}

Open in new window

Fajer39Author Commented:
Something has to be wrong, just try to add [25, 50, 75, 100]. Also when I watch it with the breakpoints in chrome DevT, when it finish sorting, it also updates the original array which I don't want.

*What should I use instead append in this case?
Alexandre SimõesManager / Technology SpecialistCommented:
1. To keep the original array unchanged, you need to "clone" it.
Currently you're just creating a pointer to a variable. Changing that variable also changes the array.
To clona an array you can use the slice(0) trick:
var sortPrices = prices.slice(0);

Open in new window


2. The append itself is correct, you just need to move it sou of the loop.

Here's the function changed to comply with what I just said:
function sortPrices(prices) {
  var sortPrices = prices.slice(0);

  //bubble sort
  for (i=0; i < sortPrices.length; i++) {
    for (j=0; j < sortPrices.length -i; j++) {
      if (sortPrices[j] > sortPrices[j+1]) {
        var temp = sortPrices[j];
        sortPrices[j] = sortPrices[j+1];
        sortPrices[j+1] = temp;
      }
    }
  }

  var pPrices = [];
  for (i=0; i < sortPrices.length; i++) {
    pPrices.push("<p>" + sortPrices[i] + "</p>");
  }
  $(".after-sale").append(pPrices.join(''));
}

Open in new window

Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Fajer39Author Commented:
Please see this - http://www.awesomescreenshot.com/image/334029/2218649113e96479e3d322f6e3f3cbeb

Thank You, I see what you mean now...I should look at the your first code example more carefuly. That's nice, it didn't come to my mind that I can actually join the items to a string and it would be better...

But still, what's wrong with the sorting?
Alexandre SimõesManager / Technology SpecialistCommented:
Ah, I got it.
It's comparing strings instead of numbers!

Use the parseInt on your comparison :
if (parseInt(sortPrices[j])  > parseInt (sortPrices[j+1]))  {

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Fajer39Author Commented:
You're the man, thanks a lot!

But why? Why the val() returns a string when the input is type of number?

I've got a better solution maybe -> var price = $("#price").val()*1; and it works. But you solved it, no Q about it :-)
Alexandre SimõesManager / Technology SpecialistCommented:
Yeah, both solutions work, just yours is an implicit type transformation. It only works because Javascript is a dynamic language!
(which is cool but should be used with caution)

Why this happens?
Because the value comes from a text box, which always produces text :-)
It doesn't really care about what you type.
Fajer39Author Commented:
Ok Thanks :-)
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.