Tags:algorithmsJavaScript

Category: Front End

common sorting algorithms

  1. Bubble sort
    /**
     * Bubble Sort
     * @param arr given an unsorted array
     * @returns {Array} return an sorted array
     */
    bubbleSort(arr) {
        const tempArr = [...arr];
        let isSort = false;
        for(let i =0;i < tempArr.length; i++ ){
            isSort = false;
            for( let j = 0;j < tempArr.length - i -1; j++) {
                if(tempArr[j] > tempArr[j+1]) {
                    [tempArr[j],tempArr[j+1]] = [tempArr[j+1],tempArr[j]];
                    isSort = true;
                }
            }
            // if not swap this run, jump out loop
            // nested loop will set isSort = true, so !isSort = true means function does not go into nested loop
            if(!isSort) {
                break;
            }
        }
        return tempArr;
    }
  1. Insetion Sort
    /**
     * Insertion Sort
     * @param arr given an unsorted array
     * @returns {Array}return an sorted array
     */
    insertionSort(arr) {

        const tempArr = [...arr];

        for(let i = 1;i<tempArr.length;i++) {
            for( let j= i-1; j >= 0;j--) {
                if(tempArr[j]>tempArr[j+1]) {
                    [tempArr[j],tempArr[j+1]] = [tempArr[j+1],tempArr[j]];
                }
            }
        }
        return tempArr
    }
}