[0005 · js] sort () integer, floating point pressed the size of the scheduling problem

Js a sorting code following a one-dimensional array of integers:

	var arr = [1, 3, 5, 2, 5];
	console.log(arr.sort());
	//输出结果如下:
	//Array(5)
	//0: 1
	//1: 2
	//2: 3
	//3: 5
	//4: 5

When the array is inconsistent when the integer part digits of problems, such as:

	var arr = [1, 30, 5, 2, 5];
	console.log(arr.sort());
	//输出结果如下:
	//Array(5)
	//0: 1
	//1: 2
	//2: 30
	//3: 5
	//4: 5

When the same one-dimensional array of floating-point, integer part when the same number of bits, there is no problem, such as:

	var arr = [1.12, 1.35, 1.01, 1.26, 1.18];
	console.log(arr.sort());
	//输出结果如下:
	//Array(5)
	//0: 1.01
	//1: 1.12
	//2: 1.18
	//3: 1.26
	//4: 1.35

The inconsistent digit integer part, the following problem occurs. such as:

	var arr = [10.12, 9.23, 10.01, 20.26, 10.18];
	//var arr = ['10.12', '9.23', '10.01', '20.26', '10.18']; //结果一致
	console.log(arr.sort());
	//输出结果如下:
	//Array(5)
	//0: 10.01
	//1: 10.12
	//2: 10.18
	//3: 20.26
	//4: 9.23

This problem should come from sort () function of the internal mechanism, temporarily do not consider here. For sort of Digital, resolved using custom ordering, as follows (an integer of one dimension can be solved Similarly, omitted):

	var arr = [10.12, 9.23, 10.01, 20.26, 10.18];
	console.log(arr.sort(function(a,b){return a-b}));
	//输出结果如下:
	//Array(5)
	//0: 9.23
	//1: 10.01
	//2: 10.12
	//3: 10.18
	//4: 20.26

arr.sort () in the function (a, b) {} method, wherein a, b are any two values in the array arr, the method returns the return value is greater than n 0 arranged in order, in reverse order of less than 0
* equal to 0, no pure digital and other issues not consider
this point to address the sort () integer, floating point pressed the size of the scheduling problem. Welcome to put forward their own views on this, we will continue to update.

Guess you like

Origin blog.csdn.net/HoD_DoH/article/details/92831723