This is the fourth day of my participation in the More text Challenge. For details, see more text Challenge

Sorting is not about comparing sizes. Sorting is about comparing and swapping

Bubble sort

Bubble sort is where you move smaller elements forward or larger elements back. A comparison is a comparison of two adjacent elements, and an exchange also occurs between the two elements. The larger numbers move slowly to the back, and the smaller ones move slowly forward, like bubbles rising to the surface of the water, so it’s called bubble sorting.

  • Bubble sort process
  1. Compare adjacent elements. If the first one is bigger than the second, swap them both.
  2. Do the same for each pair of adjacent elements, starting with the first pair and ending with the last pair. At this point, the last element should be the largest.
  3. Repeat these steps for all the elements except the last one.
  4. Keep repeating this step with fewer and fewer elements each time until there are no pairs of numbers to compare

Code implementation

var arr = [4.1.3.6.5.7];
function compare(a,b){// After the comparison, we need to find out whether the exchange is required
    if (a > b) return true;
    else return false;
}
function exchange(arr,a,b){// Swap the values in the ab position in the array
    vartemp = arr[a]; arr[a] = arr[b]; Arr [b] = temp; }function sort(arr){
    for (var  i = 0; i < arr.length; i++){for (var j = 0; j < arr.length -1 -i; j++){
            if (compare(arr[j],arr[j + 1])){
                exchange(arr,j,j + 1);
            }
        }
    }
}
sort(arr);
console.log(arr);
Copy the code

Selection sort

Select sort first finds the smallest (large) element in the unsorted sequence and stores it at the beginning of the sorted sequence. Then, it continues to find the smallest (large) element from the remaining unsorted elements and places it at the end of the sorted sequence. And so on until all the elements are sorted.

Code implementation

var arr = [4.1.3.6.5.7];
function compare(a,b){// After the comparison, we need to find out whether the exchange is required
    if (a < b) return true;
    else return false;
}
function exchange(arr,a,b){// Swap the values in the ab position in the array
    var temp = arr[a];
    arr[a] = arr[b];
    arr[b] = temp;
}
// Select sort, inner loop, each circle to select the largest, and then put behind
function sort(arr){
    for (var  i = 0; i < arr.length; i++){var maxIndex = 0;
        for (var j = 0; j < arr.length-i; j++){if (compare(arr[maxIndex],arr[j])){
                maxIndex = j;
            }
        }
        exchange(arr,maxIndex,arr.length - 1 -i);
    }
}
sort(arr);
console.log(arr);
Copy the code