Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Sorting an array means to arrange its elements in increasing order.
- Write a JavaScript function sortArray(arr) 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 strict";
- function sortArray(arr) {
- var i, j, tmp, tmp2;
- for (i = 0; i < arr.length - 1; i += 1) {
- tmp = i;
- for (j = i + 1; j < arr.length; j += 1) {
- if (arr[j] < arr[tmp]) {
- tmp = j;
- }
- }
- if (tmp != i) {
- tmp2 = arr[tmp];
- arr[tmp] = arr[i];
- arr[i] = tmp2;
- }
- }
- return arr;
- }
- console.log(sortArray([5, 4, 3, 2, 1]));
- console.log(sortArray([12, 12, 50, 2, 6, 22, 51, 712, 6, 3, 3]));
- console.log(sortArray([5, 3, 1, 5, 2, 3, 1, 5, 3, 1]));
- 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