The realization method of animation demonstration effect of JavaScript sort algorithm _javascript skills

Source: Internet
Author: User
Tags setinterval

Before you know that someone is asking themselves to write a bubble sort algorithm how to use Html,css,javascript to show the sort process. It's kind of interesting. Some time ago to write a. Here is a record of the implementation process.

The basic idea is to use the DOM structure to express the value of each step of the order.

Question one: How do you show a step-by-step process of JavaScript sorting?

Some of the ideas I've tried:

1. Let JavaScript pause and slow down.

The JavaScript sort is very fast, and the first thing I think about is getting the sort to slow down, so that we can see its implementation. Each loop of the sort lets it stop 300ms before proceeding. How to stop it. I checked that JavaScript doesn't seem to have a function like sleep (). Pause does not work, but you can find a way to achieve the same effect as the pause. Like doing something unrelated in a loop.

The first attempt was made while (true) to perform an empty operation all the time. Perform some time before returning to the sorting logic. The code is roughly like this:

for (var i = 0; i < 3; i++) {
	Document.writeln (i);//dom action 
	var now = new Date (). GetTime (); 
	while (new Date (). GetTime ()-now < 3000) {} 
}

Slow is slowing down.  But with too much resources, the DOM doesn't change in the sort process until the sort ends and the DOM becomes sorted. However, if you set a breakpoint step by step, you can see a step-by-step change in the order. It is estimated that this operation is too resource-intensive, causing the browser to give a command of the DOM operation but has not been given the resources to perform DOM operations. So the real DOM operation when the JS code execution is over.
So it's still not implemented to let JavaScript sort slow down.

Another way to get JavaScript to pause:

When I wrote this article, I thought of a way to make JavaScript stop.  That is the AJAX synchronization request, and the timeout operation. Which is to put an AJAX request in place to stop, synchronize the request, and then set the timeout. The time to timeout is the time we want to pause. To avoid the server returning our AJAX request before the timeout request is reached. You can run a program similar to sleep () on the server side. Thus ensuring that Ajax does not return. The direct timeout then returns to our loop. But it's just an idea. Interested can go and try.

2. Closures and timers. This kind of thinking doesn't need to slow down the sorting process. Instead, the array changes are used in the closure cache sort process. Then use settimeout to determine the order in which each array state is displayed. Put code similar to the following in the sort loop.

(function () {
  var Thearr = Arr.slice ();//backup settimeout for current array state
  (function () {
    bubblesortdom (Thearr);// The sort DOM operation.
  },500*timecount);
  The order of the timecount++;//timers.
}) ();

But later found that such a written word code will be relatively large, the logic has to modify the place will be a bit more. There are a lot of limitations, such as getting the sort animation to speed up or slow down is almost difficult. So we have to find another way.

3. The array state in the cache sort.

Which is in the sort process. Saves the state of each round loop of an array to an array. Then use this array to save the sort state in turn. Just add one sentence to the sort.

This.pushhis (Arr.slice (), i-1,j,k,temp);

That's all you need is a setinterval (). and can be very convenient to achieve faster and slower animation. Logic is also better understood.

Question two: How to achieve the speed and slow down of JavaScript sort animation.

We have a third way of using the problem.  Gets an array of arr that holds the sort state of each step.  Then we can use a setinterval () timer to show the sort state step by step. If you want to speed up or slow down. On Clearinterval (), modify the execution interval of the timer, SetInterval (), and start the execution of the position in the array from the previous timer.

Question three: What about an array that uses a recursive implementation? Do not operate on the original array?

The sort that is implemented using recursion. It may not operate on an array, just the final return of a sorted array. So how do we get the complete state of the array in the sort?

such as quick sort.

At the beginning, I didn't consider animations, and my implementation was this:

function QuickSort (arr) {
var len = Arr.length,leftarr=[],rightarr=[],tag;
if (len<2) {return
arr;
}
tag = arr[0];
for (i=1;i<len;i++) {
if (arr[i]<=tag) {
Leftarr.push (arr[i))
}else{
Rightarr.push (Arr[i]);
}
Return QuickSort (Leftarr). Concat (Tag,quicksort (Rightarr));

Then, to consider the animation, I rewrote its logic so that it was implemented on the same number of arrays. In fact, in the recursive time passed the current sub-array in the original array in the beginning position. The operation is done on the original array.

Two methods are used to implement the method. Slightly different in the sort logic.

The first one is the contrast with the distance first. Meet smaller than yourself and put yourself in front of yourself. Loop ordinal number +1. Bigger than yourself. Put the last face of the current sorted array, and the loop ordinal is unchanged. Until the arrangement is complete.
The disadvantage of this approach is that even an ordered array. It will also rearrange.

The second method is to set a bit of contrast in addition to the mark bit. Encounter smaller than yourself, put to the front, mark bit position +1, mark bit and contrast bit between all move to the back a position.
Met a bigger one than himself. The mark bit is unchanged, the contrast bit +1.
The disadvantage of this approach is that there are too many operations on the array. The advantage is that the ordered array will not be sorted again.

Mode one:

function QuickSort (Arr,a,b,qarr) {

var len = arr.length,leftarr=[],rightarr=[],tag,i,k,len_l,len_r,lb,ra,temp;
if (a = = undefined && b = = undefined) {
a = 0; b= arr.length-1;//initializes the starting position.
}
if (Qarr = = undefined) {
Qarr = Arr.slice ();
}

if (len = = 2 && arr[0] = = arr[1]) | | LEN<2) {return
arr;
}

tag = Qarr[a];
for (i = 1; i < Len;) {
if (qarr[a+i]<=tag) {
leftarr.push (qarr[a+i]);
QARR[A+I-1] = Qarr[a+i];
Qarr[a+i] = tag;
K = a+i;
i++;
} else{
if (leftarr.length+rightarr.length = = len-1) {break
;
}
temp = Qarr[a+i];
Qarr[a+i] = qarr[b-rightarr.length];
Qarr[b-rightarr.length] = temp;
Rightarr.push (temp);
K = a+i-1;
}
This.pushhis (Qarr.slice (), a,b,k);
}

len_l = leftarr.length;
Len_r = rightarr.length;
if (len_l== 0) {
lb = A;
} else{
lb = a+len_l-1;
This.sort (Leftarr,a,lb,qarr);
}

if (Len_r = = 0) {
ra = b;
} else{
ra = b + 1-len_r;
This.sort (Rightarr,ra,b,qarr)
} return
Qarr
}

Mode two:

function QuickSort2 (Arr,a,b,qarr) {var len = Arr.length,leftarr=[],rightarr=[],tag,i,j,k,temp,len_l,len_r,lb,ra; 
  if (a = = undefined && b = = undefined) {a = 0; b= arr.length-1;//initializes the starting position. 
  } if (Qarr = = undefined) {Qarr = Arr.slice (); 
  } if (len<2) {return arr; 
  } if (len = = 2 && arr[0] = = Arr[1]) {return arr; 
  tag = Qarr[a]; for (i = 1,k = 0; i < Len;) 
      {if (Qarr[a+i]>=tag) {Rightarr.push (qarr[a+i]); 
    i++; 
      }else{temp = Qarr[a+i]; 
        for (j = a+i;j>a+k;j--) {Qarr[j] = qarr[j-1]; 
      This.pushhis (Qarr.slice (), a,b,a+k); 
      } Qarr[a+k] = temp; 
      Leftarr.push (temp); 
      k++; 
    i++; 
  } this.pushhis (Qarr.slice (), a,b,a+k,i-1); 
  } len_l = Leftarr.length; 
  Len_r = Rightarr.length; 
  if (len_l== 0) {lb = A; 
    }else{lb = a+len_l-1; 
  This.sort (Leftarr,a,lb,qarr); 
  } if (Len_r = = 0) {RA = b; }else{RA =B + 1-len_r; 
This.sort (Rightarr,ra,b,qarr)} return Qarr;  }

The exact difference is shown in the following animation.

Question four: The fluency of the animation.

The DOM operation of the sort animation is much quicker.  Here I do the optimization just so that each sort step involves only one DOM operation. All by JavaScript stitching, one replacement. Similar to the following code.

Effect Chart:

The main implementation:

Bubble sort JavaScript Animation demo
Insert sort JavaScript Animation demo
Select Sort JavaScript Animation demo
Quick Sort JavaScript Animation demo
Merge sort JavaScript Animation demo
Hill sort JavaScript Animation demo

The above is small series for everyone to bring the JavaScript sort algorithm animation demo effect of the implementation of the whole content, I hope that we support cloud Habitat Community ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.