Advertisement
dimipan80

Sort Array (Selection Sort)

Nov 12th, 2014
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Sorting an array means to arrange its elements in increasing order.
  2. Write a JavaScript function sortArray(arr) to sort an array. Use the "selection sort" algorithm:
  3. find the smallest element, move it at the first position, find the smallest from the rest,
  4. move it at the second position, etc. Write JS program arraySorter.js that invokes your function
  5. with the sample input data below and prints the output at the console. */
  6.  
  7. "use strict";
  8.  
  9. function sortArray(arr) {
  10.     var i, j, tmp, tmp2;
  11.     for (i = 0; i < arr.length - 1; i += 1) {
  12.         tmp = i;
  13.         for (j = i + 1; j < arr.length; j += 1) {
  14.             if (arr[j] < arr[tmp]) {
  15.                 tmp = j;
  16.             }
  17.         }
  18.         if (tmp != i) {
  19.             tmp2 = arr[tmp];
  20.             arr[tmp] = arr[i];
  21.             arr[i] = tmp2;
  22.         }
  23.     }
  24.  
  25.     return arr;
  26. }
  27.  
  28. console.log(sortArray([5, 4, 3, 2, 1]));
  29. console.log(sortArray([12, 12, 50, 2, 6, 22, 51, 712, 6, 3, 3]));
  30. console.log(sortArray([5, 3, 1, 5, 2, 3, 1, 5, 3, 1]));
  31. console.log(sortArray([8.4, 9.8, 6.5, 0.4, 12.2, 3.2, 1.8, 2.45, 4.6, 5.6, 1.65e-05]));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement