1, Bubble sorting
Basic idea: compare the keywords of adjacent records between two pairs. If they are in reverse order, they will be exchanged until there are no records in reverse order.
1. Authentic bubble algorithm:
function BubbleSort(arr){
var i,j;
for(var i=0;i<arr.length-1;i++){
for(var j=arr.length-1;j>=i;j--){ //j cycle from back to front
if(arr[j-1]>arr[j]){ //If the former is greater than the latter
var temp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
}
}
}
return arr;
}
2. Improved bubbling algorithm:
function BubbleSort(arr){
var i,j;
var flag=true;
for(var i=0;i<arr.length-1 && flag;i++){ //Loop if flag is true
flag=false;
for(var j=arr.length-1;j>=i;j--){
if(arr[j-1]>arr[j]){
var temp=arr[j];
arr[j]=arr[j-1];
arr[j-1]=temp;
flag=true;
}
}
}
return arr;
}
3. Complexity analysis:
Time complexity:
The best case: the tables to be sorted are ordered, and only n-1 comparisons are made, with O(n) complexity;
In the worst case, the sequence table is in reverse order. Compare 1 + 2 + 3 + +(n-1)=n*(n-1)/2 times. Complexity O(n^2)
2, Simple selection sorting
1. Basic idea: select the record with the smallest keyword from n-i+1 records through the comparison of n-i sub keywords, and exchange it with the I (1 < = I < = n) record.
function SelectSort(arr){
var i,j,min;
for(var i=0;i<arr.length-1;i++){
min=i;
for(var j=i+1;j<arr.length-1;j++){
if(arr[min]>arr[j])
min=j;
}
if(i!=min){
var temp=arr[min];
arr[min]=arr[i];
arr[i]=temp;
}
}
return arr;
}
2. Complexity analysis
Features: fewer times of moving data, saving time.
The i-th sorting requires n-i keyword comparison, 1 + 2 + 3 + +(n-1)=n*(n-1)/2 times. For the number of exchanges, the best case is 0, and the worst case is n-1. The total time complexity is O(n^2). Slightly better than bubbling in performance.
3, Direct insert sort
1. Basic idea: insert a record into an ordered table that has already been arranged, so as to get a new ordered table with the number of records increased by 1.
function InsertSort(arr){
var i,j;
for(var i=1;i<arr.length;i++){
if(arr[i]<arr[i-1]){
var temp=arr[i];
for(var j=i-1;arr[j]>temp;j--)
arr[j+1]=arr[j];
arr[j+1]=temp;
}
}
return arr;
}
2. Complexity analysis
The best case is that the table is ordered, only the comparison between Arr[i] and Arr[i-1] is needed, and n-1 times are compared. The time complexity is O(n)
Worst case: table is in reverse order, compare (n+2)(n-1)/2 times, and move (n+4)(n-1)/2 times.