Based on the deep understanding of php bubble sort algorithm

  • 2020-06-12 08:35:35
  • OfStack

The basic idea of exchange sorting: compare the data to be sorted in pairs. If there is a reverse sorting, exchange it until all the data are sorted.
The & # 8226; The basic idea of bubble sort:
1. Scan all the data from back to front. If the two adjacent Numbers are in reverse order, they will be exchanged. The first bubble
2. Scan the last one to the second from back to front. If the two adjacent Numbers are in reverse order, they will be exchanged. -- Second bubble
3. Do this in turn, until the n-1 bubble is performed, or until there is no inversion in one of the bubbles.


<script>
var arr = [15,8,7,9,10,0];
var _len = arr.length;
alert(" Before sorting: "+arr);
var exchange=0;
var temp = 0;
for(var i=0; i<arr.length;i++)
{
  exchange=0;
  for(var j=arr.length;j>=i;j--)
  {
     if(arr[j] < arr[i])
     {
       temp = arr[j];
       arr[j] = arr[i];
       arr[i] = temp;
       exchange = 1;      
     }
  }
  if(exchange == 0)
  {
     break;
  }
}
alert(" After sorting: "+ arr);
</script>


Related articles: