Advertisement
Stann

Selection-Sort-Algorithm

Jul 20th, 2014
262
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. Write a JavaScript function sortArray(value) to sort an array. Use the "selection sort" algorithm: find the smallest element, move it at the first position, find the smallest from the rest, move it at the second position, etc. Write JS program arraySorter.js that invokes your function with the sample input data below and prints the output at the console. Use a second array.
  2.  
  3. function sortArray(arr) {
  4.     var replaceIndex = 0;
  5.     var select = arr;
  6.     for (var i = 0; i < arr.length; i++) {
  7.         select = select.slice(0);// this is the rest of the array after last iteration
  8.         Array.min = function(arr) {
  9.             return Math.min.apply(Math, select);
  10.         };
  11.         var minimum = Array.min(select);
  12.         var position = select.indexOf(minimum);
  13.         arr[replaceIndex] = select[position];
  14.         replaceIndex++;
  15.         select.splice(position, 1);//remove sorted element
  16.     };
  17.     console.log(arr.join(', '));
  18. }
  19. sortArray([5, 4, 3, 2, 1]);
  20. sortArray([12, 12, 50, 2, 6, 22, 51, 712, 6, 3, 3]);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement