Home > Web Front-end > JS Tutorial > body text

Detailed explanation of javascript array deduplication and quick sort algorithm examples

伊谢尔伦
Release: 2017-07-24 09:23:21
Original
1981 people have browsed it

Array deduplication

Principle: Define an object obj, and then use the array element as the attribute name of obj, and use whether the attribute name is repeated to determine the duplication


var unique = function(arr){
  let obj = {};
  let newArr = [];
  arr.forEach(function(x){
    if(!obj[x]){ //如果对象中没有该元素对应的属性
      obj[x] = true;
      newArr.push(x);
    }
  });
  return newArr;
}
Copy after login

Use the quick sort algorithm to sort the array

This includes two effects. One is to use the characteristics of quick sort to achieve deduplication and quick sort. , the other is quick sorting without deduplication.

Principle: Obtain the target array, select an element as the flag, traverse the remaining elements, put them on the right if they are larger than the flag, and put them on the left if they are smaller than the flag.

Special note: There are elements equal to the flag bit. If you store equal elements, deduplication will be achieved. If you store them, they will not be deduplicated.


var quickSort = function(arr){
  if(arr.length <= 1){
    return arr;
  }
  //定义一个左数组,定义一个右数组
  let leftArr = [];
  let rightArr = [];
  //选定一个参照值
  let tag = arr[0];
  /*
   * 使用如下方式判断,会把重复元素去掉,就实现了快排的同时去重
   */
  for(let i = 0; i < arr.length; i++){
    if(arr[i] < tag){ //将比tag小的元素放在左数组中
      leftArr.push(arr[i]);
    }
    if(arr[i] > tag){ //将比tag大的元素放在右数组中
      rightArr.push(arr[i]);
    }
  }
  /*
   * 使用如下方式就是使用快排进行排序,不去重
   */
  for(let i = 1; i < arr.length; i++){
    if(arr[i] < tag){ //将比tag小的元素放在左数组中
      leftArr.push(arr[i]);
    }else{ //将比tag大的元素放在右数组中
      rightArr.push(arr[i]);
    }
  }
  //递归调用
  return [].concat(quickSort(leftArr),[tag],quickSort(rightArr));
}
Copy after login

The above is the detailed content of Detailed explanation of javascript array deduplication and quick sort algorithm examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!