JS and PHP code to write eight large sorting algorithm _javascript skills

Source: Internet
Author: User
Tags array length pow

From the learning data structure began to contact with a variety of algorithms, but since the completion of the exam has never been practiced, when the development is also when to use when to check, now learning JavaScript, take advantage of this time and then the various basic algorithms to organize again, Write the code in the form of JS and PHP syntax, respectively.
1. Bubble sort
principle: The proximity of the number 22 is compared, from small to large or from large to small in order to exchange, such a trip past, the largest or smallest number is exchanged to the last one, and then start from the beginning of the 22 exchange, until the end of the second digit
time complexity: average condition: O (n2) Best case: O (N) worst case: O (N2)
Complexity of space: O (1)
Stability: stability

JavaScript syntax
 var array = [23,0,32,45,56,75,43,0,34];

 for (var i = 0; i < array.length i++)
 {
  var issort = true;
  for (var j = 0; J < array.length-1-I; j + +)
  {
  if (Array[j] > array[j+1])
  {
   Issort = false;
   
    var temp = array[j];
   ARRAY[J] = array[j + 1];
   Array[j + 1] = temp;
  }
  }
  if (Issort)
  {break
  ;
  }
 }
 Console.log (array);

   
<?php
 $array = [23,0,32,45,56,75,43,0,34];

 for ($i = 0; $i < count ($array); $i + +)
 {
  $isSort = true;
  for ($j = 0; $j < count ($array)-1; $j + +)
  {
  if ($array [$j] > $array [$j +1])
  {
   $isSort = false;
   $temp = $array [$j];
   $array [$j] = $array [$j + 1];
   $array [$j + 1] = $temp;
  }
  }
  if ($isSort)
  {break
  ;
  }
 }
 Var_dump ($array);
? >
  

2. Simple selection Sort
principle: by n-i The comparison between the secondary key words, from the N-i+1 records to select the smallest keyword records, and the first (1<=I<=N) record Exchange simple choice of sorting performance slightly better than bubble sort
time complexity: average condition: O (n2) Best case: O (N) worst case: O (N2)
Complexity of space: O (1)
Stability: unstable

JavaScript
  var array = [23,0,32,45,56,75,43,0,34];

  for (var i = 0; i < array.length-1; i++)
  {
   var pos = i;
   for (var j = i + 1; j < array.length;j++)
   {
    if (Array[j] < Array[pos])
    {
     pos=j
    }
   } var temp=array[i];
   Array[i]=array[pos];
   array[pos]=temp;
  }
  Console.log (array);

<?php
  $array = [23,0,32,45,56,75,43,0,34];
  for ($i = 0; $i < count ($array); $i + +)
 {
  $pos = $i;
  for ($j = $i + 1; $j < count ($array); $j + +)
  {
   if ($array [$j] < $array [$pos])
   {
    $pos = $j;
   }
  }
  $temp = $array [$i];
  $array [$i] = $array [$pos];
  $array [$pos] = $temp;
 }
 Var_dump ($array);

? >

3. Direct Insertion Sort
principle: insert a record into a sorted ordered table to get a new ordered table with a record number of 1.             That is, the 1th record of the sequence is first considered as an ordered subsequence, and then inserted from the 2nd record, until the entire sequence is ordered. Better than bubble method and select sort performance
time complexity: average condition: O (n2) Best case: O (N) worst case: O (N2)
Complexity of space: O (1)
Stability: stability

JavaScript
  var array = [23,0,32,45,56,75,43,0,34];
  for (var j = 0;j < array.length;j++) {
   var key = Array[j];
   var i = j-1;
   while (i > 1 && array[i] > key)
   {
    array[i + 1] = Array[i];
    i = i-1;
   }
   Array[i + 1] = key;
  }
  Console.log (array);

<?php
 //Direct Insert sort
  $array = [23,0,32,45,56,75,43,0,34];
  for ($i = 0; $i < count ($array); $i + +)
 {
  $key = $array [$i];
  $j = $i-1;
  while ($j > 1 && $array [$j] > $key)
  {
   $array [$j +1] = $array [$j];
   $j = $j-1;
  }
  $array [$j + 1] = $key;
 }
 Var_dump ($array);
? >

4. Quick Sort
principle: by a trip to sort the data to be sorted into two separate parts, where all of the data is smaller than the other part of all the data, and then the two parts of the data in this way to quickly sort the whole process can be recursive, This achieves the entire data into an ordered sequence.
time Complexity: average: O (nlog2n) best case: O (nlog2n) worst case: O (N2)
Complexity of space: O (NLOG2N)

Stability: unstable

//javascript fast sort var array = [23,0,32,45,56,75,43,0,34]; var quickSort = function (arr) {if (arr.length <= 1) {return arr;}
      Checks the number of elements in the array, or returns if less than or equal to 1.
      var pivotindex = Math.floor (ARR.LENGTH/2);//var pivot = arr.splice (pivotindex,1) [0];//Select Datum (pivot) and separate it from the original array.
      var left = [];//defines two empty arrays, which are used to store the two subsets of one right and the other to var right-hand = [];
      for (var i = 0; i < arr.length; i++)//iterate over the array, less than the elements of "datum" into the left subset, the element larger than the datum into the right subset.
        {if (Arr[i] < pivot) {Left.push (arr[i]);
        else {Right.push (arr[i]);
    QuickSort (left). Concat ([pivot], QuickSort (right));//use recursion to repeat the process, you can get the sorted array.
    };
    var newarray=quicksort (array);

Console.log (NewArray); 
 <?php $array = [23,0,32,45,56,75,43,0,34];
      function Quick_sort ($arr) {///first determine whether the need to continue $length = count ($arr);
      if ($length <= 1) {return $arr; $base _num = $arr [0];//Select a ruler to select the first element//Initialize two arrays $left _array = Array ();//Less than $right of the ruler _array = Array ()//is greater than the ruler's for ($i =1; $i < $length; $i + +) {//traverse all elements except the ruler, put in two arrays by size relationship if ($base _num > $arr [$i])
        {//Put the left array $left _array[] = $arr [$i];
        else {//Put the right $right _array[] = $arr [$i];
      }//And then to the left and right of the array to do the same sort of processing/recursive call this function, and record the result $left _array = Quick_sort ($left _array);
      $right _array = Quick_sort ($right _array);
    Merges the left ruler right return Array_merge ($left _array, Array ($base _num), $right _array);
        $newArray =quick_sort ($array); Var_dump ($newArray);?> 

5. Hill sort 
principle: First, the entire backlog of records to be sorted into a number of sub sequences are directly inserted into the order, the entire sequence of records in the "Basic order", and then the whole record of the direct insertion sequence.
time Complexity: average: O (n√n) best case: O (nlog2n) worst case: O (N2)
Complexity of space: O (1)

Stability: unstable

JavaScript Hill sort
    var array = [23,0,32,45,56,75,43,0,34];
    var shellsort = function (arr)
    {
      var length=arr.length;
      var h=1;
      while (H<LENGTH/3)
      {
        h=3*h+1;//set interval
      } while
      (H>=1)
      {for
        (var i=h; i<length; i++)
        {for
          (var j=i; j>=h && arr[j]<arr[j-h]; j-=h)
          {
            var temp =arr[j-h];
            ARR[J-H]=ARR[J];
            Arr[j]=temp
          }
        }
        H= (h-1)/3;
      }
      return arr;
    }
    var NewArray = shellsort (array);
    Console.log (NewArray);

<?php
//Hill sort
    $array = [23,0,32,45,56,75,43,0,34];
    function Shellsort ($arr)
    {
      $length =count ($arr);
      $h =1;
      while ($h < $length/3)
      {
        $h =3* $h +1;//set interval
      } while
      ($h >=1)
      {for
        ($i = $h; $i <$ Length $i + +)
        {for
          ($j = $i; $j >= $h && $arr [$j]< $arr [$j-$h]; $j-= $h)
          {
             $temp = $arr [$j-$h];
             $arr [$j-$h]= $arr [$j];
             $arr [$j]= $temp;
          }
        }
        $h = ($h-1)/3;
      }
      return $arr;
    }
    $newArray = Shellsort ($array);
    Var_dump ($newArray)
?>

6. Merge sort
principle: Assuming that the initial sequence contains n records, it can be considered n ordered subsequence, each subsequence length is 1, then 22 merge, get (not less than n/2 smallest integer) a length of 2 or 1 ordinal subsequence, and then 22 merge,... So repeat until you get an ordered sequence of length n.
time Complexity: average: O (nlog2n) best case: O (nlog2n) worst case: O (nlog2n)
Complexity of space: O (1)

Stability: stable  

JavaScript merge sort function IsArray1 (arr) {if (Object.prototype.toString.call (arr) = = ' [Object Array] ') {R
      Eturn true;
      }else{return false;
      } function Merge (Left,right) {var result=[];
      if (!isarray1 (left)) {left = left];
      } if (!isarray1) {right = right]; while (Left.length > 0&& right.length >0) {if (left[0]<right[0)) {Result.push (lef
        T.shift ());
        }else{Result.push (Right.shift ());
    } return Result.concat (left). Concat (right);
      function MergeSort (arr) {var len=arr.length;
      var Lim, work=[];
      var i,j,k;
      if (Len ==1) {return arr;
      for (i=0;i<len;i++) {Work.push (arr[i]);
      } work.push ([]);
        for (lim=len;lim>1;) {//lim is a packet length for (j=0,k=0;k<lim;j++,k=k+2) {work[j]=merge (work[k],work[k+1]);
    } work[j]=[];    Lim=math.floor ((lim+1)/2);
    return work[0];
    
    var array = [23,0,32,45,56,75,43,0,34];

 Console.log (MergeSort (array));
<?php//merge sort function mergesort (& $arr) {$len = count ($arr);//Get array length Msort ($arr, 0, $len
    -1); The program function Msort (& $arr, $left, $right) {if ($left < $right) {//Description The number of sequences in the substring
        More than 1 elements, then need to split, sorting, merging//computing split position, length/2 $center = Floor (($left + $right)/2);
        Recursive calls to the left are sorted again: Msort ($arr, $left, $center);
        Recursive calls to the right are sorted again Msort ($arr, $center +1, $right);
      Merge sort results Mergearray ($arr, $left, $center, $right);  }///merge two ordered arrays into an ordered array function Mergearray (& $arr, $left, $center, $right) {//Set two start position tags $a _i
      = $left;
      $b _i = $center +1;
          while ($a _i<= $center && $b _i<= $right) {//when array A and group B have no bounds (if ($arr [$a _i] < $arr [$b _i]) {
        $temp [] = $arr [$a _i++];
        else {$temp [] = $arr [$b _i++]; }//Determine if the elements in array A are all used up, and if not, insert them all into the C array: while ($a _i <= $centeR) {$temp [] = $arr [$a _i++];
      //Judge whether the elements in array B are all used up, and if not, insert them all into the C array: while ($b _i <= $right) {$temp [] = $arr [$b _i++]; ///$ARRC the sorted portions within the $arr: for ($i =0, $len =count ($temp); $i < $len; $i + +) {$arr [$left + $i] = $t
      emp[$i];
    }} $arr = Array (23,0,32,45,56,75,43,0,34);
    MergeSort ($arr);

 Var_dump ($arr);?>

7. Heap Sorting
principle: Heap Sorting is the method of using the heap to sort. The basic idea is to construct the sequence to be sorted into a large heap. At this point, the maximum value of the entire sequence is the root node of the top of the heap. Remove it (in fact, swap it with the end element of the heap array, at which point the end element is the maximum), The remaining n-1 sequences are then reconstructed into a heap, which will get the secondary large value of n elements. So repeatedly executed, you get an ordered sequence.
time Complexity: average: O (nlog2n) best case: O (nlog2n) worst case: O (nlog2n)
Complexity of space: O (1)
Stability: unstable

JavaScript heap Sort var array = [23,0,32,45,56,75,43,0,34]; function Heapsort (array) {for (var i = Math.floor (ARRAY.LENGTH/2); I >= 0; i--) {Heapadjust (Array, I, array.length-1); Building array arrays into a large top heap} for (i = array.length-1 i >= 0; i--) {/* Swap the root node out */var temp
        = Array[i];
        Array[i] = array[0];
        ARRAY[0] = temp;
      /* The remaining array continues to be constructed into a large top heap * * Heapadjust (array, 0, i-1);
    } return array; The function heapadjust (array, start, max) {var temp = Array[start];//temp is the value for the root node for (var j = 2 * STAR T J < Max;
        J *= 2) {if (J < Max && Array[j] < Array[j + 1]) {//Get the subscript ++j of the larger child;
        } if (temp >= array[j]) break;
        Array[start] = Array[j];
      start = j;
    } Array[start] = temp;
    var NewArray = heapsort (array); Console.log (NewArray);

<?php//Heap sort function heapsort (& $arr) {#初始化大顶堆 initheap ($arr, 0, Count ($arr)-1);
      #开始交换首尾节点, and then adjust the heap at one end node at a time until the remaining element for ($end = count ($arr)-1; $end > 0; $end-) {$temp = $arr [0];
      $arr [0] = $arr [$end];
      $arr [$end] = $temp;
    Ajustnodes ($arr, 0, $end-1);
    } #初始化最大堆, starting with the last non-leaf node, the last non-leaf node number takes the entire function initheap (& $arr) {$len = count ($arr) for an array length/2;
    for ($start = Floor ($len/2)-1; $start >= 0; $start-) {ajustnodes ($arr, $start, $len-1); #调整节点 # @param $arr to resize array # @param $start Adjust the parent coordinates # @param $end to adjust array end node coordinates function ajustnodes (&$
    Arr, $start, $end) {$maxInx = $start;  $len = $end + 1;  #待调整部分长度 $leftChildInx = ($start + 1) * 2-1;  #左孩子坐标 $rightChildInx = ($start + 1) * 2; #右孩子坐标 #如果待调整部分有左孩子 if ($leftChildInx + 1 <= $len) {#获取最小节点坐标 if ($arr [$maxInx] < $arr [$left
Childinx]) {$maxInx = $leftChildInx;      #如果待调整部分有右子节点 if ($rightChildInx + 1 <= $len) {if ($arr [$maxInx] < $arr [$rightChil
        Dinx]) {$maxInx = $rightChildInx;
      #交换父节点和最大节点 if ($start!= $maxInx) {$temp = $arr [$start];
      $arr [$start] = $arr [$MAXINX];
      
      $arr [$maxInx] = $temp;
      #如果交换后的子节点还有子节点, continue to adjust if (($maxInx + 1) * 2 <= $len) {ajustnodes ($arr, $maxInx, $end);
  }} $arr = Array (23,0,32,45,56,75,43,0,34);
  Heapsort ($arr);

 Var_dump ($arr);?>

8. Cardinality sort
principle: cuts integers by number of digits to different digits, and then compares each number by each digit.  Because integers can also express strings (such as names or dates) and floating-point numbers in a particular format, cardinality sorting is not only used for integers.
time complexity: average: O (d (r+n))   Best case: O (d (N+RD)) worst case: O (d (r+n))    R: Cardinality of Keywords    d: Length   N: Number of keywords
space complexity: O (rd+n)
Stability: stable  

<?php #基数排序, where only the positive integers are sorted, as for negative numbers and floating-point numbers, you need to use the complement, you are interested in studying #计数排序 # @param $arr to sort array # @param $digit _num According to number of numbers Sort function Counting_sort (& $arr, $digit _num = False) {if ($digit _num!== false) {#如果参数 $digit _num is not empty, according to the element $ Digit_num the number of digits to sort for ($i = 0; $i < count ($arr) $i + +) {$arr _temp[$i] = Get_specific_digit ($arr [$i], $di
       Git_num);
     } else {$arr _temp = $arr;
     $max = max ($arr); $time _arr = Array ();
     #储存元素出现次数的数组 #初始化出现次数数组 for ($i = 0; $i <= $max; $i + +) {$time _arr[$i] = 0;
     #统计每个元素出现次数 for ($i = 0; $i < count ($arr _temp); $i + +) {$time _arr[$arr _temp[$i]]++; #统计每个元素比其小或相等的元素出现次数 for ($i = 0; $i < count ($time _arr)-1; $i + +) {$time _arr[$i + 1] = $time _ar
     r[$i]; #利用出现次数对数组进行排序 for ($i = count ($arr)-1; $i >= 0; $i-) {$sorted _arr[$time _arr[_temp[$arr]]-1
       = $arr [$i]; $time _arr[$arr _temp[$i]]--;
     } $arr = $sorted _arr;  Ksort ($arr);
     #忽略这次对key排序的效率损耗} #计算某个数的位数 function Get_digit ($number) {$i = 1;
     while ($number >= pow ($i)) {$i + +;
   return $i; #获取某个数字的从个位算起的第i位数 function Get_specific_digit ($num, $i) {if ($num < POW ($i-1)) {return 0
     ;
   Return floor ($num% POW ($i)/POW ($i-1));
     #基数排序, the order of count as the Sub sort procedure function Radix_sort (& $arr) {#先求出数组中最大的位数 $max = max ($arr);
 
     $max _digit = Get_digit ($max);
     for ($i = 1; $i <= $max _digit $i + +) {Counting_sort ($arr, $i);
   }} $arr = Array (23,0,32,45,56,75,43,0,34);
 
   Radix_sort ($arr);

 Var_dump ($arr);?>

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.