Array reorganization and quick sorting of JS algorithm

JS Algorithm Questions

Array deduplication

function clearArray(arr){
    
    
    new clearArray=new Array;
    for(var i;i<arr.length;i++){
    
    
        if(clearArray.indexOf('arr[i]')==-1)//如果没有匹配元素则添加,也可以用来除重
            clearArray.push(arr[i]);
    }
}

Use indexOf matching to deduplicate, and use indexof to determine whether there are duplicate elements in the array to add

quick sort algorithm

Suppose there is a string of arrays

4 1 3 5 7 2 8 9
i j

We take the first element of the array as the base value (that is, 4), and set two sentinels (pointers) to point to the first and last elements of the array respectively,

Each sentinel carries a base value to compare with the element at the corresponding position in the array (j is ahead of i), the sentinel j is compared with 9 first, and j=j-1 if it is larger than the base value, until a value less than or equal to the base value is found At this time, j temporarily stops moving, and then i starts to compare, i compares from left to right, and stops moving when it encounters a number larger than the base value

4 1 3 5 7 2 8 9
i j

Then when both i and j stop for the first time, i is at the position of 5, j is at the position of 2, and then the values ​​corresponding to i and j are exchanged

4 1 3 2 7 5 8 9
i j

After exchanging values, j still starts to move first, and compares from the current position to the next one, repeating the previous operation until i, j meet

4 1 3 2 7 5 8 9
i,j

When j also moves to 2, i and j meet, stop moving at this time, exchange the value of the meeting position (that is, the value 2 corresponding to i, j) and the base value

2 1 3 4 7 5 8 9
i,j

At this time, we can find that the values ​​on the left side of the sentinel are all smaller than 4, and the values ​​on the right side are all larger than 4, and then split into two arrays with 4 as the dividing line

2 1 3 4
7 5 8 9

Continue to perform quick sort on the split array until there is only one sequence.

Realize with JS

function quicksort(arr,rear,front){
    
    
    var i,j,key;//哨兵,基值
    i=rear;
    j=front;
    key=arr[rear];
    if(rear>=front)
        return 0;
    while(i<j){
    
    //i比j要小
        while(arr[j]>key&&i<j){
    
    //j先判断
            j--;
        }
        while(arr[i]<=key&&i<j){
    
    //j停止后,i开始判断
            i++;
        }
        if(i<j){
    
    
            var b;//i,j都停止了
            b=arr[i];
            arr[i]=arr[j];
            arr[j]=b;//交互i,j的值
        }
    }//ij相遇
    arr[rear]=arr[i]//相遇点的值与基值交换
    arr[i]=key;
    quicksort(arr,rear,i-1);//前半部分重复快速排序
    quicksort(arr,i+1,front);//后半部分重复快速排序
}

// var arr = [3,3,-5,6,0,2,-1,-1,3];
// console.log(arr);
// quicksort(arr,0,arr.length-1);
// console.log(arr);

Guess you like

Origin blog.csdn.net/qq_51649346/article/details/124115059