php實現7種常見排序

2022-05-04 03:45:11 字數 3704 閱讀 8283

class

test

public

function

createdata()

}$sectime = microtime

();

$this->gettimelimit($firtime, $sectime

);

return

$data

; }

//歸併排序開始

public

function mergesort($data

)

public

function mergesortmain(&$data, $from, $to

)

$middle = floor(($to + $from)/2);

$left = $this->mergesortmain($data, $from, $middle

);

$right = $this->mergesortmain($data, $middle+1, $to

);

$res = $this->sorttwosortarr($left, $right

);

return

$res

; }

public

function sorttwosortarr($arra, $arrb

) else

}if (count($arra

)) }

elseif (count($arrb

)) }

return

$res

; }

//歸併排序結束

//快速排序開始

public

function fastsort($data

)

public

function fastsortmain($start, $end, &$data

)

$middle = $this->fastsortswap($start, $end, $data

);

$this->fastsortmain($start, $middle-1, $data

);

$this->fastsortmain($middle+1, $end, $data

); }

//這個方法的作用是把 $data從start到end之間的部分 分成大於某值或者小於某值兩部分,並且返回某值的位置

public

function fastsortswap($start, $end, &$data

) else

}$data[$end] = $data[$resust_key

];

$data[$resust_key] = $flag

;

return

$resust_key

; }

//快速排序結束

//選擇排序開始

public

function selectsort($data

)

}$temp = $data[$i

];

$data[$i] = $minval

;

$data[$minkey] = $temp

; }

$sectime = microtime

();

$this->gettimelimit($firtime, $sectime

); }

//選擇排序結束

//希爾排序開始

public

function shellsort($data

)

$data[$k + $jump] = $temp

;

$j += $jump

; }

}$jump = floor($jump/2);

}$sectime = microtime

();

$this->gettimelimit($firtime, $sectime

); }

//希爾排序結束

//氣泡排序開始

public

function bubblesort($data

)

}if($flag

) }

$sectime = microtime

();

$this->gettimelimit($firtime, $sectime

); }

//氣泡排序結束

//插入排序開始

public

function insertsort($data

)

$data[$j+1] = $temp

; }

$sectime = microtime

();

$this->gettimelimit($firtime, $sectime

); }

//插入排序結束

//堆排序開始

public

function heapsort($data

)

$sectime = microtime

();

$this->gettimelimit($firtime, $sectime

); }

public

function initheap(&$data

) }

public

function swap(&$data, $i, $j

) else

}public

function down(&$data, $head, $tail

)

if ($data[$next_head] > $head_val)

else

$head = $next_head

;

$left_child = $head * 2 + 1;

$right_child = $left_child + 1;

$next_head = $left_child

; }

$data[$head] = $head_val

; }

//堆排序結束

//獲取花費時間開始

public

function gettimelimit($a, $b

)

//獲取話費時間結束

}

最後發現7種排序的效率從低到高依次為

氣泡排序

選擇排序

插入排序

希爾排序

歸併排序

堆排序快速排序

將資料量增加到1000w,也沒有看到堆排序的優勢,還是快速排序效率最高,留坑待填//todo

7種php基本排序實現方法

本文總結了一下常用的7種排序方法,並用php語言實現。1 直接插入排序 直接插入排序,插入排序的思想是 當前插入位置之前的元素有序,若插入當前位置的元素比有序元素最後乙個元素大,則什麼也pqbkgkiqpn不做,否則在有序序列中找到插入的位置,並插入 function insertsort arr ...

7種常見排序演算法的c 實現

今天心血來潮複習了一下基本的排序演算法,實現了一下,就順便發上來咯。在 裡做了注釋了 也就不多說了,直接上 吧。order algorithm.cpp 定義控制台應用程式的入口點。author netbin include stdafx.h include iostream include incl...

常見的7種排序演算法

1 氣泡排序 最簡單的一種排序演算法。先從陣列中找到最大值 或最小值 並放到陣列最左端 或最右端 然後在剩下的數字中找到次大值 或次小值 以此類推,直到陣列有序排列。演算法的時間複雜度為o n 2 氣泡排序 void bubblesort int arr,int length 2 選擇排序 嚴蔚敏版...