Bubble sort
Thought: An array of double loops, judging the left and right adjacent to the two values, large at the left of the small, if the left is larger than the right, the two sides replace the position
The length of the array is reduced by one because the array starts with 0, for example an array has 7 elements, and its length is 7, respectively.
A[0],A[1],A[2],A[3]A[4],A[5],A[6] These 7 so when you want to take the last a[6 in the array, you need to reduce the length by 1.
And why reduce I, it is because your bubble sort is to put the biggest to the last one, such as the first cycle of the time to sort out, the last one is the largest, there is no need to take him in the second cycle in the size of it, and if not minus I, Only one maximum can be discharged (which is used to find the largest value in the array), and so on ...
var arr=[2,1,3,5,4,6];
function Test (arr) {
for (Var i=0;i<arr.length-1;i++) {//-1 is because you want to loop the length of this array-1 times. Because the maximum value of the previous round is not likely to appear behind it.
for (Var j=0;j<arr.length-1-i;j++) {//-1-i is because his length is smaller than the paragraph,
if (Arr[j]>arr[j+1]) {
var temp=arr[j];
ARR[J]=ARR[J+1];
ARR[J+1]=ARR[J];
}
}
}
return arr;
}
Quick Sort
Thought: To find an intermediate dividing point of the array, divide the array into the left and right areas, use the values to compare the median, the small left area, the large put-in area, and then recursive call, to achieve a quick sort
function Test1 (arr) {
if (arr.length<=1) {return arr}
var left=[],right=[],mid=arr.splice (Math.floor (ARR.LENGTH/2), 1);
for (Var i=0;i<arr.length;i++) {
if (Arr[i]<mid) {
Left.push (Arr[i]);
}else{
Right.push (Arr[i]);
}
}
Return Test1 (left). Concat (Mid,test1 (right));
}
Two-point Search
Non-recursive invocation, suitable for negative numeric lookup of arrays
function Test3 (Data,das) {
var max=data.length-1;
var min=0;
while (Min<=max) {
var Mid=math.floor ((Min+max)/2,1);
if (Data[mid]==das) {
return mid;
} else if (Das>data[mid]) {
min=mid+1;
}else{
Max=mid-1;
}
}
return false;
}
JS Bubble sort, quick sort, binary search