As one of the classic sorting algorithms, bubbling sorting also has several implementations in JavaScript.
Temporary variables are declared in some of the most common implementations, and in other implementations that do not have to declare temporary variables, they may only support numeric arrays or string arrays (either).
Here are two implementations of "No need to declare temporary variables" and "apply to numeric arrays and string arrays."
Version ES5:
vararr = [5, 25, 2, 53, 22, 10];functionBubblesort (arr) { for(varj = 1, len = arr.length; J < Len; J + +){ for(vari = 0; i < len-j; i++) { if(Arr[i] > arr[i + 1]) {arr[i+ 1] = [Arr[i], arr[i] = arr[i + 1]][0]; Execution Order}}}returnarr;} Console.log (Bubblesort (arr). toString ()); //' 2,5,10,22,25,53 '
Important: Before Arr[i + 1] is re-assigned, Arr[i] has been re-assigned, and its original value has been saved to the 0 index position of the array before arr[i] is re-assigned to the value.
Version ES6:
Let arr = [' Root ', ' Harold ', ' sameen ', ' John '= (arr) + = {for (Let j = 1, len = Arr.leng Th J < Len; J + +) {for (let i = 0; i < len-j; i++) { if (Arr[i] > arr[i + 1 ]) { + 1]] = [Arr[i + 1], arr[i]];//Deconstruction } }}return// ' Harold,john,root,sameen '
Important: Understand the new deconstructed assignment expression ECMAScript 6.
The end
JavaScript implementation of bubble sort algorithm