js bubble sort and quick sort principle and method

Interviews often encounter this problem, so in order, in order to understand.

Sort method often used in two ways, bubble sort and quick sort.

1. Start with a quick sort

Principle: Each time the size of two adjacent numbers compare, by the first round of sorting, find maximum into the back, the value of the second round to find two large rear discharge.

Code:

 sort(arr: Array<any>) {
        for(let i = 0; i<arr.length;i++) {
            for(let j = 0;j<arr.length-i-1;j++){
                let tmp = arr[j];
                if(arr[j] > arr[j+1]){
                    arr[j] = arr[j+1];
                    arr[j+1] = tmp;
                }
            }
        }
        return arr;
    }

For example, performing [19,49,89,5,8,34,1,5,63] the array, through the first cycle will be taken out on the final surface 89, then the previous data of the second round of circulation, would get 63, and so on.

NOTE: If the array in descending order, the above code arr [j]> arr [j + 1] is smaller than the symbol to be changed.

 

2. Bubble Sort

Principle: take an intermediate value between the values ​​through the array and compared to the tree, it is smaller than the left discharge, it is larger than the right place, and then sequentially and recursively the left and right array, in order to achieve the purpose of ordering .

Code:

 quickSort(arr:Array<any>):Array<any> {
        if( arr.length < 1) {
            return  arr;
        }
        let num = Math.floor(arr.length/2);
                let middle = arr.splice(num,1)[0];
        let leftArr = [];
        let rightArr = [];
        for(let i = 0;i < arr.length; i++) {
            if (middle > arr[i]) {
                leftArr.push(arr[i]);
            } else {
                rightArr.push(arr[i]);
            }
        }
        return this.quickSort(leftArr).concat([middle],this.quickSort(rightArr));
    }

 Similarly, if you want to give an array of diminishing the middel> arr [i] is greater than to less than the can.

Guess you like

Origin www.cnblogs.com/saiying/p/11316278.html