Data Structure and Algorithms in JavaScript Version--Foundation

This is a sequel to the previous one. Data Structure and Algorithms in JavaScript Version--Basic (1) This article was fi...
aggregate
tree
Sorting and Searching Algorithms

This is a sequel to the previous one. Data Structure and Algorithms in JavaScript Version--Basic (1)

This article was first published on a personal blog Data Structure and Algorithms in JavaScript Version--Basic (2)

Thank you for pointing out any errors

aggregate

A collection is made up of an unordered and unique set of items.

Unordered means that access cannot be made through subscript values, only that one of the same objects exists in the collection

In fact, ES5 already contains Array classes, ES6 already contains Set classes, which can be used directly

Code implements a Set class

function Set() { this.item = {} Set.prototype.add = function (value) { if (this.has(value)) { return false } this.item[value] = value return true } Set.prototype.has = function (value) { return this.item.hasOwnProperty(value) } Set.prototype.remove = function (value) { if (!this.has(value)) { return false } delete this.item[value] return true } Set.prototype.clear = function () { this.item = {} } Set.prototype.size = function () { return Object.keys(this.item).length } Set.prototype.value = function () { return Object.keys(this.item) } } Copy Code

We can do some operations on sets as follows:

  • Intersection: For a given set, returns a new set containing elements common to both sets.
  • Union: For a given set of two, returns a new set containing all the elements in both sets.
  • Difference set: For a given set of two, returns a new set containing all elements that exist in the first set and do not exist in the second set.
  • Subset: Verifies that a given set is a subset of another set.Union code implementation:
Set.prototype.union = function (otherSet) { let unionSet = new Set() let value = this.value() for(let i = 0; i< value.length; i++){ unionSet.add(value[i]) } let v = otherSet.value() for(let i = 0; i< value.length; i++){ unionSet.add(v[i]) } return unionSet } Copy Code

Intersection code implementation:

Set.prototype.intersection = function (otherSet) { let intersectionSet = new Set() let value = this.value() for(let i = 0; i< value.length; i++){ let it = value[i] if (otherSet.has(it)) { intersectionSet.add(it) } } return intersectionSet } Copy Code

Difference code implementation:

Set.prototype.difference = function (otherSet) { let differenceSet = new Set() let value = this.value() for(let i = 0; i< value.length; i++){ let it = value[i] if (!otherSet.has(it)) { differenceSet.add(it) } } return differenceSet } Copy Code

Subset code implementation:

Set.prototype.sub = function (otherSet) { let subSet = new Set() let value = this.value() for(let i = 0; i< value.length; i++){ let it = value[i] if (!otherSet.has(it)) { return false } } return true } Copy Code

tree

Trees are a non-linear data structure that stores data hierarchically.Trees are used to store data with hierarchical relationships, such as files in a file system; trees are also used to store ordered lists.

Common tree structures in life: organization charts, family genealogy

Compared to arrays, chained lists, and hash tables:

  1. Array:
    • Access according to subscript value, high efficiency
    • It is inefficient to find corresponding locations based on elements.
  2. Chain List:
    • Chain lists are fairly efficient at insertion and deletion
    • Finding is inefficient and requires starting from scratch each time.
  3. Hash table:
    • Insert, delete, and find efficiently
    • Space utilization is low; elements in a hash table are out of order and cannot be looked up in a fixed order; special values such as maximum\minimum values in a hash table cannot be quickly found.
  4. Tree:
    • Each data structure has a specific application scenario and it cannot be said that the tree structure is better than the others.
    • The tree combines the advantages of the above data structure (of course, not enough to outperform other data structures, such as generally less efficient than a hash table)
    • Fixed some of the shortcomings of the above data structure
    • In order to simulate some application scenarios, it is more convenient to use the tree structure (1, the tree structure can represent a one-to-many relationship; 2, the directory structure of the file.)

A detailed description of the tree refers to one of my previous articles: Data Structure and Algorithms for Javascript Version--Binary Tree

Sorting and Searching Algorithms

Large O Complexity Representation

Large O time complexity does not actually represent the actual execution time of the code, but the trend of code execution time with the increase of data size. Therefore, it is also called asymptotic time complexity, or simply time complexity.

Addition rule: The total complexity equals the complexity of the code with the largest magnitude

Multiplication rule: The complexity of nested code is equal to the product of the complexity of code inside and outside the nesting

Sorting algorithm

Bubble sort, select sort, insert sort, merge sort, count sort, cardinality sort, Hill sort, heap sort, bucket sort

Simple sort: bubble sort, select sort, insert sort

Advanced Sorting: Hill Sorting, Quick Sorting

Bubble sort

Compare all the adjacent items and swap the first one if it is larger than the second.Element items move up to the correct order

class ArrList { constructor () { this.arr = [] } insert(item) { this.arr.push(item) } toString(){ return this.arr.join('-') } bubbleSort () { let len = this.arr.length for (let j = len - 1; j >= 0; j--) { // The inner loop arranges the maximum (or minimum) to the right in each round. // The second round of looping only requires action to remove the remaining rightmost values, so the outer loop decreases gradually. for (let i = 0; i < j; i++) { if (this.arr[i] > this.arr[i + 1]) { let temp = this.arr[i] this.arr[i] = this.arr[i + 1] this.arr[i + 1] = temp } } } } } // Use let list = new ArrList() // Add data list.insert(22) list.insert(222) list.insert(2) list.insert(12) alert(list) list.bubbleSort() alert(list) Copy Code
Select Sort

Find the smallest value in the data structure and put it first, then the second smallest value and put it second, and so on

class ArrList { constructor () { this.arr = [] } insert(item) { this.arr.push(item) } toString(){ return this.arr.join('-') } selectionSort () { let len = this.arr.length for(let j = 0;j< len - 1; j++){ let min = j // Save the minimum subscript with an initial value of 0 for(let i = min + 1; i < len; i++){ if (this.arr[min] > this.arr[i]) { min = i // Take out the minimum value } } // Exchange elements at min and j locations if (min !== j) { let temp = this.arr[min] this.arr[min] = this.arr[j] this.arr[j] = temp } } } } // Use let list = new ArrList() // Add data list.insert(22) list.insert(222) list.insert(2) list.insert(12) alert(list) list.selectionSort() alert(list) Copy Code
Insert Sort

Core: Locally ordered.Assume that the first item is sorted.Next, it compares with the second item - should the second item stay in place or before the first one? Then the first two items are sorted correctly, followed by the third item (should it be inserted in the first, second or third position), and so on

class ArrList { constructor () { this.arr = [] } insert(item) { this.arr.push(item) } toString(){ return this.arr.join('-') } insertSort () { let len = this.arr.length for(let i = 1; i < len; i++){ // The first one on the left by default is ordered let temp = this.arr[i] // Compare elements from subscript 1 to the left of that element // If the element is smaller than the left, move the left element one place to the right in turn until you find a position larger than the left element, where you place the element, that is, to complete the sequential ordering let j = i while(this.arr[j - 1] > temp && j > 0){ this.arr[j] = this.arr[j - 1] j-- } this.arr[j] = temp } } } // Use let list = new ArrList() // Add data list.insert(22) list.insert(222) list.insert(2) list.insert(12) alert(list) list.insertSort() alert(list) Copy Code

The time complexity of the previous sorting algorithms is O(N^2)

Shell Sort

Is an efficient and improved version of insert sorting and is faster than insert sorting.Also known as reduced incremental sorting

Principle: Grouping data that needs to be sorted by a certain increment, using a direct insert sort algorithm to sort each group; as the increment decreases, each group contains more and more keywords, and when the increment decreases to 1, the entire file is just grouped.- From Baidu Encyclopedia: Shell Sort

There are three levels of circular nesting:

  1. Outermost: constantly changing increments
  2. Middle-tier looping: Grouping in increments and sorting the groups by insertion
  3. Innermost: elements within a group are inserted in the correct position
class ArrList { constructor () { this.arr = [] } insert(item) { this.arr.push(item) } toString(){ return this.arr.join('-') } shellSort () { let len = this.arr.length // Initialization Increment let gap = Math.floor(len / 2) // Loop operation (gap decreasing) while(gap >= 1) { // Group groups at gap intervals and sort groups by insertion for (let i = gap; i < len; i++) { let temp = this.arr[i] let j = i while(this.arr[j - gap] > temp && j - gap > 1){ this.arr[j] = this.arr[j - gap] j -= gap } this.arr[j] = temp } gap = Math.floor( gap / 2) } } } // Use let list = new ArrList() // Add data list.insert(22) list.insert(222) list.insert(2) list.insert(12) alert(list) list.shellSort() alert(list) Copy Code

Quick Sort

Sorting process:

  1. Select a base value
  2. In the data to be sorted, those smaller than the base value are placed to the left of the base value, and those larger than the base value are placed to the right of the base value.
  3. Do the above for the left and right side of the data
class ArrList { constructor () { this.arr = [] } insert(item) { this.arr.push(item) } toString(){ return this.arr.join('-') } quickSort (arrData = this.arr) { if(arrData.length <= 1) return arrData let pivotIndex = Math.floor(arrData.length / 2) let pivot = arrData.splice(pivotIndex, 1)[0] // Take out the base value let left = [] // Place data smaller than base let right = [] // Place the array larger than the base value for(let i = 0; i < arrData.length; i++ ){ if(arrData[i] < pivot){ left.push(arrData[i] ) } else { right.push(arrData[i] ) } } this.arr = this.quickSort(left).concat([pivot], this.quickSort(right)) return this.arr } } // Use let list = new ArrList() // Add data list.insert(22) list.insert(222) list.insert(2) list.insert(12) alert(list) list.quickSort() alert(list) Copy Code

These two articles are basic algorithms and data structures that I think front-end engineers should understand and learn

Thank you for pointing out any errors

Thank you for your reading

17 May 2020, 20:10 | Views: 4492

Add new comment

For adding a comment, please log in
or create account

0 comments