Bubble && Select && Fast && Binary Search

Bubble Sort

let arr=[12,6,3,8,88,66,14,87,9,5,55]; //正正
for(let x=0; x<arr.length; x++){
    for(let y=x+1;y<arr.length;y++){
        if(arr[x] > arr[y]){
            let tmp=arr[x];
            arr[x]=arr[y];
            arr[y]=tmp;
        }
    }
}
console.log(arr);

selection sort

 //选择排序
   let arr = [25, 66, 58, 78, 96, 14, 68, 85, 12];

   function selectSort(array) { //正序

      for (let x = 0; x < array.length; x++) {

         let selectIndex = x;//记录最小索引

         for (y = x + 1; y < array.length; y++) {

            if (array[selectIndex] > array[y]) {

               selectIndex = y;
            }
         }
         // console.log('第' + x + '遍:', selectIndex);

         if (selectIndex != x) {

            let tmp = array[x];

            array[x] = array[selectIndex];

            array[selectIndex] = tmp;
         }
         // console.log(array);
      }
      return array;

   }
   console.log(selectSort(arr));

quick sort

    let arr = [25, 55, 98, 48, 62, 27, 69, 44];
     function quickSort(array) {
 
         if (array.length <= 1) {
 
             return array;
         }
 
         let minddle = array[0];
         let left = [], right = [];
 
         for (let x = 1; x < array.length; x++) {
 
             if (x == minddle) continue;
             if (array[x] < minddle) {
                 left.push(array[x]);
             } else if (array[x] > minddle) {
 
                 right.push(array[x]);
 
             }
         }
 
         return quickSort(left).concat([minddle],quickSort(right));
 
     }
     console.log(quickSort(arr)); 

binary search

 //二分查找

    let arr = [1, 3, 4, 44, 65, 78, 89];

    function minddleFind(array, item) {

        let low = 0, high = array.length - 1;

        while (low <= high) {
            let mid = Math.floor((high + low) / 2);

            if (array[mid] == item) {
                return mid;
            }

            if (array[mid] > item) {
                high = mid - 1;

            } else if (array[mid] < item) {
                low = mid + 1;
            }
        }

        return null;
    }
    console.log(minddleFind(arr, 22));

Guess you like

Origin blog.csdn.net/weixin_45753588/article/details/124415554