Detailed tutorial on javascript data structure and algorithm

Source: Internet
Author: User
Tags arithmetic arithmetic operators data structures require variable scope

The algorithm is a broad concept, we write any program can be called algorithms, even in the fridge to put the elephant, but also through the door, put, close the door of such planning, we can also be regarded as an algorithm. It can be said that the simple algorithm is the human instinct. The knowledge of the algorithm is learned from the experience of predecessors. For complex problems to classify, abstract, to help us out of the slash-and-burn era, the system grasps an algorithm process.

With the growth of their own knowledge, whether it is to do front-end, server or client, any programmer will start to face more complex problems, algorithms and data structures become more indispensable.

The front-end engineer should be the one who needs to focus on algorithms and data structure. Data structure and algorithms do not take into account the need to get started, so front-end engineers, if they do not pay attention to the basic knowledge of algorithms and data structures, are likely to fall into the career development dilemma that has been very little growing. The future of the Web UI, by no means by a few selector operation plus link can handle. More and more complex products and base libraries require a solid data structure and algorithms to navigate.

In the past few years, thanks to platforms like Node.js and SpiderMonkey, JavaScript is increasingly used for server-side programming, where JavaScript is out of the browser and programmers find that they need more traditional languages (such as C + + and Java). The tools provided. These tools include traditional data structures (such as lists, stacks, queues, graphs, etc.) that also include traditional sorting and lookup algorithms. This series of blogs is about how to use these data structures and algorithms when using JavaScript for server-side programming.

JavaScript programmers will find this series useful because the book discusses how to implement data structures and algorithms under the JavaScript language constraints. These limitations include: arrays are objects, ubiquitous global variables, prototype-based object models, and so on. JavaScript, as a programming language, has a bad reputation, and this series of blogs will showcase the good side of JavaScript to implement efficient data structures and algorithms.

The only data structures that are familiar to programmers who have not studied computers in schools are arrays. Arrays are a great choice when it comes to dealing with problems, but arrays are too primitive for many complex problems. Most programmers acknowledge the fact that for many programming problems, when they present a suitable data structure, the design and implementation of algorithms to solve these problems becomes extremely easy.

The binary lookup number (BST) is one such example. The purpose of designing a binary difference tree is to find the minimum and maximum value of a set of data, because this data structure naturally extends a lookup algorithm, which is more efficient than the best query algorithm at present. Programmers who are unfamiliar with binary lookup trees may use a simpler data structure, but with a discount in efficiency.

Learning algorithms are very important because many algorithms can often be used to solve the same problem. For efficient programmers, it's important to know how efficient that algorithm is. For example, there are now at least six or seven sorting algorithms, and if you know that a quick sort is more efficient than selecting a sort, it makes the sorting process more efficient. For example, the algorithm to implement a linear lookup is simple, but if you know that sometimes a binary lookup can be twice times faster than a linear lookup, you're bound to write a better program.

In-depth learning of data structures and algorithms not only makes it easier to know which data structures and algorithms are more efficient, but also knows how to find the structure and algorithms that are best suited to solving the problem at hand. Writing programs, especially when it comes to JavaScript writing programs, is often weighed.

JavaScript's programming environment and model

This chapter describes the JavaScript programming environment and basic programming modules that will be used in subsequent chapters to define data structures and implement various algorithms.

1.javascript has always been a program language that runs in browsers, but in the past few years, these things have changed and JavaScript can be executed as a desktop program. or executed on the server. Describes a programming environment: the JavaScript shell, which is part of the integrated JavaScript programming environment SpiderMonkey provided by Mozilla.

2. Declaring and initializing variables

JavaScript variables are global variables by default, and, strictly speaking, they do not even need to be declared before they are used. If you initialize a JavaScript variable that is not declared beforehand, the variable becomes a global variable. All, in programming, we follow the custom of compiling languages such as C + + or Java, making declarations before using variables, the benefit of which is that declared variables are local variables. The scope of the variables is discussed in more detail later in this chapter.

To declare a variable in JavaScript, you need to use the keyword Var, followed by the variable name, or followed by an assignment expression.

var number;
var name;
var rate = 1.2;
var greeting = "Hello world!";
var flag = false;


Arithmetic operators and mathematical library functions in 3.javascript

JavaScript uses standard arithmetic operators

+ Plus,-minus, * multiply,/except,% to rest


JavaScript also has a mathematical library that can be used to perform advanced operations such as square roots, absolute values, and trigonometric functions. Arithmetic operators follow the standard order of operations, and you can use parentheses to change the order of operations.

var x = 3;
var y = 1.1;
Console.log (x + y)
console.log (x * y)
console.log (x + y) * (XY);
var z = 9;
Console.log (Math.sqrt (z));
Console.log (Math.Abs (y/x))


If the calculation precision does not have to be as accurate as above, you can convert the number to a fixed precision

var x = 3;
var y = 1.1;
var z = x * y;
Console.log (z.tofixed (2));


2. Judging structure

Based on the value of the Boolean expression, the structure is judged to allow the program to execute the statement to the program that can be executed. Commonly used if and switch statements

If there are three different forms

A simple if statement
If-else statement
If-else-if statement

The following shows a simple if statement

var mid =;
var height = m;
var low = 1;
var current =;
var found =-1;
if (current < mid) {
mid = (current-low)/2
}


The following shows the If-else statement

var mid =;
var height = m;
var low = 1;
var current =;
var found =-1;
if (current < mid) {
mid = (current-low)/2;
else {
mid = (current + height)/2;
}



The following demo if-else-if

    var mid = 25;    
 var height = 50;
    var low = 1;
    var current = 13;
    var found = -1;     if  (current < mid)  {       
 mid =  (Current - low)  / 2;     } else if  (current > mid)  {         mid =  (current + height) &NBSP;/2     }  else {        found = current     } 



Another judgment structure is a switch statement, and the code that uses the statement is clearer when there are multiple simple choices.

3. Circular structure

Two commonly used loop structures: the while loop and the For loop.

If you want the condition to be true, just execute a set of statements and select the while loop, showing how the while loop works

While loop

var number = 1;
var sum = 0;
while (number < one) {
sum + = number;
++number
}
console.log (sum)//55



If you want to execute a set of statements by the number of executions, select the For loop. Here is a for loop that asks 1 to 10 for integer summation and

var number = 1;
var sum = 0;
for (var number =1 number < number++) {
sum + = number;
}
console.log (sum)


When you access an array, you often use a For loop, as follows:

var number = [3,7,12,22,100];
var sum = 0;
for (var i = 0; i < number.length ++i) {
sum + = Number[i];
}
console.log (sum)//144


4. function


JavaScript provides two ways to customize a function, one with a return value, and one that has no return value (this function is sometimes called a subroutine or a void function).

Here's how to customize how a function with a return value calls the function in JavaScript.

function factorial (number) {
var product = one;
for (var i = number; I >= 1;-i) {
product *= 1
} return
product;
}
Console.log (factorial (4))



The following example shows how to define a function that does not return a value, using it not to get its return value, but to perform the actions defined in the function.

A subroutine or void function in JavaScript

function curve (arr, amount) {for
(var i = 0; i < arr.length; ++i) {
Arr[i] + = amount;
}
var grades = [77,73,74,81.90];
Curve (grades,5);
Console.log (Grades)



In JavaScript, the parameters of a function are passed by value, without arguments passed by reference. But JavaScript has objects that hold references, such as arrays, which, as in the example above, are passed by reference.


5. Variable Scope

The scope of a variable refers to a variable that can be accessed by those objects in the program. Variable scopes in JavaScript are defined as function scopes.
This means that the value of a variable is visible within the function that defines the variable. and nested functions that are defined within the function can also access the variable.

In the main program, if you define a variable outside of the function, the variable has a global scope, which means that the variable can be accessed in any part of the program that includes the function body. Here's a short program that shows how the scope works.

function Showscope () {return
scope;
var scope = "global";
Console.log (scope); Global
Console.log (Showscope ());//global


The scope of a variable defined within the Showscope () function has a local scope, while defining a variable scope in the main program is a global variable. Although two variable names are the same, they differ in scope, and the values that are obtained when they are defined are not the same.

These behaviors are normal and expected, but if you omit the keyword var when you define a variable, everything changes. JavaScript allows you to define a variable without using the keyword VAR, but the consequence is that the defined variable automatically owns the global scope, even if you define the variable within a function, it is also a global variable.

The following examples are the consequences of abusing global variables.

function Showscope () {
scope = ' local ';
return scope;
scope = "global";
Console.log (scope);  Global
Console.log (Showscope ()); Local
Console.log (scope)//local



In the above example, the keyword VAR is omitted because the variable scope is defined within the Showscope () function. So when you assign the string "local" to the variable, you actually change the value of the scope variable in the main program. Therefore, when you define a variable, you should always start with Var to avoid similar errors.


As we mentioned earlier, JavaScript has a function scope, meaning that JavaScript has no block-level scope, unlike many other modern programming languages. Using a block-level scope, you can define a variable in a section of code that is visible only within a block, leaving the block of code missing. In C + + or Java for loops, we often see examples of this

for (int i = 1; I <= ++i) {
count << ' Hello world! ' << end;
}


Although JavaScript does not have a block-level scope, when we write a for loop, we assume it has:

for (var i = 1; I <=10; ++i) {
console.log ("hello,world!")
}


The reason for this is, do not want to develop their own bad programming habits helper!

6. Recursion

JavaScript allows functions to be called recursively, and the previously defined factorial () function can also use recursion to define

function factorial (number)  {    if  ( number == 1)  {        return number      } else {        return number *  Factorial (number - 1)     } console.log (factorial (5))  //120 


When a function is called recursively, the result of the function is temporarily suspended when the recursion is not complete. To illustrate this process, a diagram shows the process of executing a function when the factorial () function is invoked with 5 as a parameter.


5 * Factorial (4)
5 * 4 * factorial (3)
5 * 4 * 3 * factorial (2)
5 * 4 * 3 * 2 * factorial (1)
5 * 4 * 3 * 2 * 1
5 * 4 * 3 * 2
5 * 4 * 6
5 * 24
120



In most cases, JavaScript has the ability to handle hierarchical recursive calls, but Baobuzzi some algorithms require a recursive depth beyond the processing power of JavaScript, at which point we need to find an iterative solution to the algorithm. Any function that can be recursively defined can be rewritten as an iterative program, which is to be kept in mind.

Object and object-oriented programming

Data structures are to be implemented as objects. JavaScript provides a variety of ways to create and use objects. The following shows, creating objects, and creating and using methods and properties in objects.

Objects are created by defining the constructor that contains the property and method declarations and following the definition of the method after the constructor. The following is a constructor that checks the bank account object:

function Checking (amount) {
this.balance = amount;//property
this.deposit = deposit;//Method
This.withdraw = withdraw;//method
this.tostring = tostring;//Method
}


The This keyword is used to bind methods and properties to an instance of an object, and here's how we define the method that is declared above


Function Deposit (amount) {
this.balance + = amount;
}
function withdraw (amount) {
if (amount <= this.balance) {
this.balance-= amount;
}
if (Amount > This.balance) {
Console.log ("insufficient funds");
}
function toString () {return
"Balance:" + this.balance;
}



Here, again, we use the This keyword and the Balance property to let the JavaScript interpreter specify that we are referencing the object's Balance property

The complete definition and testing of the checking object are given below

Function checking (amount) {    this.balance = amount; //Properties      this.deposit = deposit; //Method     this.withdraw =  withdraw;//method     this.tostring = tostring;//Method} function deposit (amount)  {    this.balance += amount;} function withdraw (amount)  {     if  (amount <= this.balance)  {      
  this.balance -= amount; &NBSP;&NBSP;&NBSP;&NBSP}     if  (amount > this.balance)  { 
       console.log ("Insufficient balance"); &NBSP;&NBSP;&NBSP;&NBSP}} function tostring () {    return  balance:  + 
this.balance;
} var account = new checking (500);
Account.deposit (1000); Console.log (Account.tostring ());//Balance: 1Account.withdraw (750); Console.log (account.tostring ())//Balance: 750 Account.withdraw (a)  //balance is insufficient console.log (account.tostring ());//Balance : 750


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.