Using JS to implement a simple algorithm

Source: Internet
Author: User

One. Bubble sort

var arr1=[3,9,2,7,0,8,4];
for (Var i=0;i<arr1.length;i++) {
for (Var j=i+1;j<arr1.length;j++) {
var temp=0;
if (Arr1[i]>arr1[j]) {
Temp=arr1[i];
ARR1[I]=ARR1[J];
Arr1[j]=temp;
}
}
}
alert (ARR1);

Two. Quick Sort

var a=[3,5,0,9,2,7,5];
function QuickSort (arr) {
var len=a.length;
if (len<=1) return arr;

function sort (low,height) {
var pivot=a[low];
var i=low,j=height,t;
if (I>J) return false;
while (I!=J) {
while (A[J]>=PIVOT&&I<J) {
j--;
}
while (A[I]<=PIVOT&&I<J) {
i++;
}
if (i<j) {//put bigger than pivot to the right, small to the left
T=a[i];
A[I]=A[J];
a[j]=t;
}
}
At this point I and J point to the same number and switch the number to pivot.
A[low]=a[i];
A[i]=pivot;
Recursion: Sort the number on the left of the pivot once and the number on the right
Sort (low,i-1);
Sort (i+1,height);
}
Call this sort of function
Sort (0,len-1);
return A;
}
Alert (QuickSort (a));

Using JS to implement a simple algorithm

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.