Home > Web Front-end > JS Tutorial > Introducing the dichotomy method in js and the example code for deduplication

Introducing the dichotomy method in js and the example code for deduplication

零下一度
Release: 2017-07-17 16:04:35
Original
1583 people have browsed it
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		
	</body>
	<script type="text/javascript">
		var arr =[1,2,3,4,5,6,7,8,9,0,8,5,5,4,3];
		//创建一个数组
		function findInArr(arr,n){
			//循环数组中的每一项如果它的每一个i项与n相等就返回继续执行
			for (var i=0;i<arr.length;i++){
				if (arr[i] == n){
					return true;
				}
			}
			    return false;
		}
		function removeDup(arr,s,e){
//			判断这个数组,的开始顺序,和这个数组是不是首项和尾项相等
			if (s>e) {
				return false;
			} else if(s==e){
				return [arr[s]];
			}
//			将数组进行二分,找到中间项,将数组分为两部分
			var c= Math.floor((s+e)/2);
			var l = removeDup(arr,s,c);
			var r = removeDup(arr,c + 1,e);
			for (var i=0;i< r.length; i++) {
				if (!findInArr(l,r[i])) {
					l.push(r[i])
				}
			}
			return l;
		}
		console.log(removeDup(arr,0,arr.length-1))
	</script>
</html>
Copy after login

Algorithms are a wonderful thing, and I hope we can communicate more with them.

The above is the detailed content of Introducing the dichotomy method in js and the example code for deduplication. 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