Posted By

Piotrek290 on 05/21/10


Tagged

js array for sorting


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

dipser
Piotrek290


Sorting


 / Published in: JavaScript
 

  1. // Swap elements
  2. Array.prototype.swap = function(a,b) {
  3. var t = this[a];
  4. this[a] = this[b];
  5. this[b] = t;
  6. return this;
  7. }
  8.  
  9.  
  10. // Input: [ 2,5,6,1,2,8 ]
  11. var t = [ 2,5,6,1,2,8 ];
  12. var r = t.length;
  13.  
  14. // Doing array better
  15. for(var i=0; i<r-2; ++i){
  16. for(var j=r-1; j>0; --j){
  17. if(t[j-1] > t[j]){
  18. t.swap(j-1, j);
  19. }
  20. }
  21. }
  22.  
  23. // Output: [ 1,2,2,5,6,8 ]

Report this snippet  

You need to login to post a comment.