Hi You, I am Tade

You are here: Home / Lập trình / Sắp xếp phần tử trong mảng php

Sắp xếp phần tử trong mảng php

19 January, 2016 by Hoàng Thức

Hôm nay mình sẽ làm 1 đoạn code sắp xếp phần tử trong mảng php mà không sử dụng hàm sort trong php.

Đầu tiên tìm giá trị nhỏ nhất trong mảng. Thuật toán mình sử dung là so sánh các giá trị liên kề với nhau.


function min_array($array){
 $t=$array[0];
 $j=0;
 for($i=1;$i<count($array);$i++){
 if($t<$array[$i]){$t= $array[$i];$j=$i;$i=1;}
 }

return $t;
}

Khi bạn đổi toán tử khi so sánh 2 phần tử kề nhau ta sẽ số phần tử giá trị lớn nhất trong mảng.

</pre>
<pre> for($i=1;$i<count($array);$i++){
 if($t<$array[$i]){$t= $array[$i];$j=$i;$i=1;}
 }

Sắp xếp tăng dần

function sort_array($array){  
 for($i=1;$i<count($array);$i++){
 $j=$array[$i];
 $t=$array[$i-1];
 if($t>$j){$array[$i-1]=$j;$array[$i]=$t;$i=0;}
 
 } 
 return $array;
}


Sắp xếp giảm dần

for($i=1;$i<count($array);$i++){
 $j=$array[$i];
 $t=$array[$i-1];
 if($t<$j){$array[$i-1]=$j;$array[$i]=$t;$i=0;} 
 } 

 

Filed Under: Lập trình, Php

Comments

  1. eebest8 michael says

    8 July, 2016 at 5:52 am

    “Just wanna input on few general things, The website style is perfect, the articles is really good D.”

  • Home
  • About
  • Donate

Danh mục

  • Blog
  • Lập trình
  • Laravel
  • MYSQL
  • Php
  • Thủ thuật máy tính
  • Vps
    • DirectAdmin
  • Wordpress
    • Plugin wordpress
    • Wordpress căn bản
    • Wordpress nâng cao
      • Custom post wordpress

Archives

  • October 2021
  • January 2021
  • December 2020
  • November 2020
  • September 2020
  • August 2020
  • September 2019
  • August 2019
  • July 2019
  • June 2018
  • August 2017
  • July 2017
  • June 2017
  • May 2017
  • March 2017
  • November 2016
  • September 2016
  • July 2016
  • June 2016
  • May 2016
  • April 2016
  • March 2016
  • January 2016
  • December 2015
  • May 2015
  • April 2015
Copyright © 2023 · HoangThuc.com · Genesis Framework