示例#1
4
文件: top10.php 项目: sunaysg/joniink
function quicksort($array)
{
    if (count($array) < 2) {
        return $array;
    }
    $left = $right = array();
    reset($array);
    $pivot_key = key($array);
    $pivot = array_shift($array);
    foreach ($array as $k => $v) {
        if ($v['times_ordered'] > $pivot['times_ordered']) {
            $left[$k] = $v;
        } else {
            $right[$k] = $v;
        }
    }
    return array_merge(quicksort($left), array($pivot_key => $pivot), quicksort($right));
}
/**
 * Função de ordenação
 * @param array $vet
 * @param int $ini Início do Array
 * @param in $fim Final do Array (tamanho do array)
 */
function quicksort(&$vet, $ini, $fim)
{
    $i = $ini;
    $j = $fim;
    $dir = 1;
    while ($i < $j) {
        if ($vet[$i] > $vet[$j]) {
            $aux = $vet[$i];
            $vet[$i] = $vet[$j];
            $vet[$j] = $aux;
            $dir = -$dir;
        }
        if ($dir == 1) {
            $j--;
        } else {
            $i++;
        }
    }
    $k = $i;
    if ($ini < $fim) {
        quicksort($vet, $ini, $k - 1);
    }
    if ($i < $fim) {
        quicksort($vet, $k + 1, $fim);
    }
}
示例#3
0
function quicksort(&$array, $l = 0, $r = 0)
{
    if ($r === 0) {
        $r = count($array) - 1;
    }
    $i = $l;
    $j = $r;
    $x = $array[($l + $r) / 2];
    do {
        while ($array[$i] < $x) {
            $i++;
        }
        while ($array[$j] > $x) {
            $j--;
        }
        if ($i <= $j) {
            if ($array[$i] > $array[$j]) {
                list($array[$i], $array[$j]) = array($array[$j], $array[$i]);
            }
            $i++;
            $j--;
        }
    } while ($i <= $j);
    if ($i < $r) {
        quicksort($array, $i, $r);
    }
    if ($j > $l) {
        quicksort($array, $l, $j);
    }
}
示例#4
0
function quicksort($array)
{
    // find array size
    $length = count($array);
    // base case test, if array of length 0 then just return array to caller
    if ($length <= 1) {
        return $array;
    } else {
        // select the last item to act as our pivot point
        $pivot = $array[$length - 1];
        // declare our two arrays to act as partitions
        $left = array();
        $right = array();
        // loop and compare each item in the array to the pivot value, place item in appropriate partition
        for ($i = 0; $i < $length - 1; $i++) {
            if ($array[$i] < $pivot) {
                $left[] = $array[$i];
            } else {
                $right[] = $array[$i];
            }
        }
        // use recursion to now sort the left and right lists
        return array_merge(quicksort($left), array($pivot), quicksort($right));
    }
}
示例#5
0
文件: e.php 项目: ironxu/aboutme
function quicksort(&$A, $p, $r)
{
    if ($p < $r) {
        $q = partition($A, $p, $r);
        quicksort($A, $p, $q - 1);
        quicksort($A, $q + 1, $r);
    }
}
 public function testArrayWithOrderElementsReverOrder()
 {
     $original = [9, 8, 7, 6, 5, 4, 3, 2, 1];
     $copy = [9, 8, 7, 6, 5, 4, 3, 2, 1];
     // Order the array copy
     sort($copy, SORT_NUMERIC);
     $this->assertEquals(quicksort($original), $copy);
 }
示例#7
0
function quicksort(&$array, $left, $right)
{
    if ($left >= $right) {
        return;
    }
    $pivot = partition($array, $left, $right);
    quicksort($array, $pivot + 1, $right);
    quicksort($array, $left, $pivot - 1);
}
示例#8
0
function quicksort(array &$array, $start, $end, $value)
{
    if ($start >= $end) {
        return;
    }
    $pivotStartIndex = pickPivot($array, $start, $end);
    $pivotNewIndex = partition($array, $start, $end, $pivotStartIndex, $value);
    quicksort($array, $start, $pivotNewIndex - 1, $value);
    quicksort($array, $pivotNewIndex + 1, $end, $value);
}
 /**
  * @dataProvider pullData
  */
 public function testLargeArraysOfRandomNumbersAreProperlySorted($unsortedArray)
 {
     $correctSorted = $unsortedArray;
     $arrayToSort = $unsortedArray;
     quicksort($arrayToSort, 0, count($arrayToSort) - 1, 'value');
     usort($correctSorted, function ($a, $b) {
         return $a['value'] - $b['value'];
     });
     $this->assertEquals($correctSorted, $arrayToSort);
 }
示例#10
0
function quicksort($vetor)
{
    if (count($vetor) <= 1) {
        return $vetor;
    }
    $chave = array_shift($vetor);
    return array_merge(quicksort(array_filter($vetor, function ($valor) use($chave) {
        return $valor < $chave;
    })), array($chave), quicksort($higher = array_filter($vetor, function ($valor) use($chave) {
        return $valor >= $chave;
    })));
}
示例#11
0
function quicksort(&$arr, $st, $end)
{
    if ($st == $end) {
        return;
    }
    $sep = $st;
    for ($i = $st + 1; $i < $end; $i++) {
        if ($arr[$i] < $arr[$st]) {
            swap($arr, ++$sep, $i);
        }
    }
    swap($arr, $st, $sep);
    quicksort($arr, $st, $sep);
    quicksort($arr, $sep + 1, $end);
}
示例#12
0
function getGachaSortByPriorityLevel(array $gachaObjectArray)
{
    if (count($gachaObjectArray) == 0) {
        return array();
    }
    $pivot = $gachaObjectArray[0];
    $left = $right = array();
    for ($i = 1; $i < count($gachaObjectArray); $i++) {
        if ($gachaObjectArray[$i]->getGachaBasePriority() < $pivot->getGachaBasePriority()) {
            $left[] = $gachaObjectArray[$i];
        } else {
            $right[] = $gachaObjectArray[$i];
        }
    }
    return array_merge(quicksort($left), array($pivot), quicksort($right));
}
示例#13
0
function quicksort($seq)
{
    if (!count($seq)) {
        return $seq;
    }
    $k = $seq[0];
    $x = $y = array();
    for ($i = count($seq); --$i;) {
        if ($seq[$i] <= $k) {
            $x[] = $seq[$i];
        } else {
            $y[] = $seq[$i];
        }
    }
    return array_merge(quicksort($x), array($k), quicksort($y));
}
示例#14
0
function quickSort($arr)
{
    $loe = $gt = array();
    if (count($arr) < 2) {
        return $arr;
    }
    $p_key = key($arr);
    $p = array_shift($arr);
    foreach ($arr as $val) {
        if ($val <= $p) {
            $loe[] = $val;
        } elseif ($val > $p) {
            $gt[] = $val;
        }
    }
    return array_merge(quicksort($loe), array($p_key => $p), quicksort($gt));
}
示例#15
0
function quicksort($input)
{
    if (empty($input)) {
        return $input;
    }
    $pivot = $input[0];
    $l = $r = array();
    for ($i = 1; $i < count($input); $i++) {
        if ($input[$i] < $pivot) {
            $l[] = $input[$i];
        } else {
            $r[] = $input[$i];
        }
    }
    $merged = array_merge(quicksort($l), array($pivot), quicksort($r));
    if (count($merged) > 1) {
        echo implode(' ', $merged), "\n";
    }
    return $merged;
}
/**
 * QuickSort Algorithm for order elements inside of an array
 *
 * @params  Array   $array  The array to order
 * @return  Array           The order array
 */
function quicksort($array = [])
{
    $length = count($array) - 1;
    if ($length < 1) {
        return $array;
    }
    $index = $length / 2;
    $pivot = $array[$index];
    // Remove element from the array
    unset($array[$index]);
    $less = [];
    $greater = [];
    // Loop over the whole array
    foreach ($array as $element) {
        $element <= $pivot ? array_push($less, $element) : array_push($greater, $element);
    }
    // Merge the whole array as a recursive call to the
    // two arrays: $less and $greater
    return array_merge(quicksort($less), [$pivot], quicksort($greater));
}
示例#17
0
 public function sort()
 {
     /** quicksort 
      * @author PageConfig em http://pageconfig.com/post/implementing-quicksort-in-php
      */
     if (count($this->dados) < 2) {
         return $this->dados;
     }
     $left = $right = array();
     reset($this->dados);
     $pivot_key = key($this->dados);
     $pivot = array_shift($this->dados);
     foreach ($this->dados as $k => $v) {
         if ($v < $pivot) {
             $left[$k] = $v;
         } else {
             $right[$k] = $v;
         }
     }
     return array_merge(quicksort($left), array($pivot_key => $pivot), quicksort($right));
 }
示例#18
0
/**
 * 递归法实现的快速排序
 * @param $seq
 * @return array
 */
function quicksort($seq)
{
    if (count($seq) > 1) {
        $k = $seq[0];
        $x = array();
        $y = array();
        $_size = count($seq);
        //do not use count($seq) in loop for.
        for ($i = 1; $i < $_size; $i++) {
            if ($seq[$i] <= $k) {
                $x[] = $seq[$i];
            } else {
                $y[] = $seq[$i];
            }
        }
        $x = quicksort($x);
        $y = quicksort($y);
        return array_merge($x, array($k), $y);
    } else {
        return $seq;
    }
}
function meine_buecher($email)
{
    $sql = "SELECT * FROM Buecher WHERE EMail LIKE '{$email}'";
    mysql_verbinden();
    $query = mysql_query($sql);
    mysql_close();
    $erg = array();
    while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
        array_push($erg, $row);
    }
    $erg = quicksort($erg, 'Datum');
    $erg = array_reverse($erg);
    return $erg;
}
示例#20
0
文件: tags.php 项目: redroot/URIKA
    function index()
    {
        $q_vars = get_url_vars();
        $sort = isset($q_vars->sort) ? $q_vars->sort : "";
        $search = isset($q_vars->search_tag) ? $q_vars->search_tag : "";
        $base = base_url();
        if ($search != "") {
            $cache = cacheFetch("tagsCache");
        } else {
            $cache = cacheFetch("tagsPopularCache");
        }
        if (isset($cache["data"]) !== false) {
            $tags = json_decode($cache["data"]);
            if (is_array($tags) || !empty($tags)) {
                // start the query_string
                $q_str = "";
                if ($search != "") {
                    $q_str = '?search_tag=' . $search . '&';
                } else {
                    $q_str = '?';
                }
                // sort links
                $sort_alpha = '<a href="' . $base . 'tags/' . $q_str . 'sort=sort-alpha-';
                $sort_total = '<a href="' . $base . 'tags/' . $q_str . 'sort=sort-total-';
                if ($sort == "sort-alpha-desc") {
                    quicksort($tags, "value");
                    $tags = array_reverse($tags);
                    $sort_alpha .= 'asc" title="List Alphabetically descending"><strong>List Alphabetically</strong></a>';
                    $sort_total .= 'desc" title="List By Total descending"><strong>List By Total</strong></a>';
                } else {
                    if ($sort == "sort-total-asc") {
                        quicksort($tags, "total");
                        $sort_alpha .= 'desc" title="List Alphabetically ascending"><strong>List Alphabetically</strong></a>';
                        $sort_total .= 'desc" title="List By Total descending"><strong>List By Total</strong></a>';
                    } else {
                        if ($sort == "sort-total-desc") {
                            quicksort($tags, "total");
                            $tags = array_reverse($tags);
                            $sort_alpha .= 'desc" title="List Alphabetically ascending"><strong>List Alphabetically</strong></a>';
                            $sort_total .= 'asc" title="List By Total ascending"><strong>List By Total</strong></a>';
                        } else {
                            quicksort($tags, "value");
                            $sort_alpha .= 'desc" title="List Alphabetically ascending"><strong>List Alphabetically</strong></a>';
                            $sort_total .= 'desc" title="List By Total descending"><strong>List By Total</strong></a>';
                        }
                    }
                }
                // grab heighest total value
                $temp_tags = $tags;
                quicksort($temp_tags, "total");
                $temp_tags = array_reverse($temp_tags);
                $highest = $temp_tags[0]->total;
                // now sort
                $tags_count = count($tags);
                $list_html = "";
                $details_html = "";
                $sort_html = 'Sort:  ' . $sort_alpha . ' <span class="sep">|</span> ' . $sort_total . ' <span class="sep">|</span> <a href="' . $base . 'tags/' . $q_str . 'tag_cloud=1" title="View popular tags as tag cloud"><strong>View as Tag Cloud</strong></a>';
                if ($search != "") {
                    $details_html = '
					<ul class="search_filters">
						<li><a href="' . $base . 'tags/" title="Remove this filter" class="remove_filter"><span class="hide">Remove</span></a> Showing tags containing "<strong>' . $q_vars->search_tag . '</strong>"</li>
						<li>' . $sort_html . '</li>
					</ul>';
                } else {
                    $details_html = '<ul class="search_filters">
						<li>Showing popular tags</li>
						<li>' . $sort_html . '</li>
					</ul>';
                }
                if (isset($q_vars->tag_cloud)) {
                    // tag cloud mode
                    // we'll have 8 font-sizes, ranging from 10-18
                    // and therefore six colours
                    $list_html .= '<div style="text-align: center;"><ul class="tag_cloud">';
                    $max = 30;
                    $min = 10;
                    $colours = array("10" => "#aaa", "11" => "#909090", "12" => "#909090", "13" => "#999", "14" => "#808080", "15" => "#808080", "16" => "#888", "17" => "#707070", "18" => "#707070", "19" => "#777", "20" => "#606060", "21" => "#606060", "22" => "#666", "23" => "#505050", "24" => "#505050", "25" => "#555", "26" => "#404040", "27" => "#404040", "28" => "#444", "29" => "#303030", "30" => "#333");
                    for ($i = 0; $i < $tags_count; $i++) {
                        if ($search != "") {
                            if (strpos($tags[$i]->value, $search) === FALSE) {
                                continue;
                            }
                        }
                        $font_size = (string) $min + round($tags[$i]->total / $highest * ($max - $min));
                        $list_html .= '<li>
							<a style="font-size: ' . $font_size . 'px; color: ' . $colours[$font_size] . ';" href="' . $base . 'browse/?tag=' . str_replace(" ", "+", $tags[$i]->value) . '" title="view uploads with this tag">
								' . $tags[$i]->value . '
								<em>' . $tags[$i]->total . '</em>
							</a>
						</li>';
                    }
                    $list_html .= '</ul><div class="clear">&nbsp;</div></div>';
                } else {
                    $list_html .= '<ul class="tag_list">';
                    for ($i = 0; $i < $tags_count; $i++) {
                        if ($search != "") {
                            if (strpos($tags[$i]->value, $q_vars->search_tag) === FALSE) {
                                continue;
                            }
                        }
                        $perc = round($tags[$i]->total / $highest * 100);
                        $list_html .= '<li>
							<a href="' . $base . 'browse/?tag=' . str_replace(" ", "+", $tags[$i]->value) . '" title="view uploads with this tag">
								' . $tags[$i]->value . '
								<em>' . $tags[$i]->total . '</em>
							</a>
							<span style="width:' . $perc . '%;" class="bar">' . $perc . '%</span>
						</li>';
                    }
                    $list_html .= '</ul>';
                }
            } else {
                $list_html = "<ul><li>No tags yet</li></ul>";
            }
            // template stuff
            $data = array("list_html" => $list_html, "details_html" => $details_html, "search" => $search);
            $this->template->write("title", "Tags");
            $this->template->write_view("content", "browse/tags", $data);
            $this->template->render();
        } else {
            redirect("", "location");
        }
    }
示例#21
0
function quicksort(array $arr, $left, $right)
{
    $i = $left;
    $j = $right;
    $separator = $arr[floor(($left + $right) / 2)];
    while ($i <= $j) {
        while ($arr[$i] < $separator) {
            $i += 1;
        }
        while ($arr[$j] > $separator) {
            $j -= 1;
        }
        if ($i <= $j) {
            $tmp = $arr[$i];
            $arr[$i] = $arr[$j];
            $arr[$j] = $tmp;
            $i += 1;
            $j -= 1;
        }
    }
    if ($left < $j) {
        $arr = quicksort($arr, $left, $j);
    }
    if ($right > $i) {
        $arr = quicksort($arr, $i, $right);
    }
    return $arr;
}
        if ($array1[$i]['value'] != $array2[$i]['value']) {
            echo "array1[{$i}]['value']={$array1[$i]}['value'], array2[{$i}]['value']={$array2[$i]}['value']<br>";
            return false;
        }
    }
    return true;
}
$limit = 100000;
$practiceDB = new Database('algorithm_practice');
$query = $practiceDB->db->prepare("SELECT * FROM sorting WHERE id <= {$limit}");
try {
    $query->execute();
    $unsortedArray = $query->fetchAll();
    $arrayToSort = $unsortedArray;
    $beginMine = microtime(true);
    quicksort($arrayToSort, 0, count($arrayToSort) - 1, 'value');
    echo 'My time: ' . (microtime(true) - $beginMine) . '<br>';
    $sortedArray =& $arrayToSort;
    unset($arrayToSort);
    $rightAnswer = $unsortedArray;
    $beginBuiltin = microtime(true);
    usort($rightAnswer, function ($a, $b) {
        return $a['value'] - $b['value'];
    });
    echo 'Builtin sort time: ' . (microtime(true) - $beginBuiltin) . '<br>';
    if (!equalValues($rightAnswer, $sortedArray)) {
        echo "error!<br>";
    }
} catch (PDOException $e) {
    echo "Query error: " . $query->errorCode;
    exit;
示例#23
0
<?php

print_r(quicksort(array(4, 5, 3, 7, 2)));
function quicksort($input)
{
    $pivot = $input[0];
    $l = $r = array();
    for ($i = 0; $i < count($input); $i++) {
        if ($input[$i] < $pivot) {
            $l[] = $input[$i];
        } elseif ($input[$i] > $pivot) {
            $r[] = $input[$i];
        }
    }
    return array_merge($l, array($pivot), $r);
}
/*
$t = fgets(STDIN);
$string = fgets(STDIN);

echo implode(' ', partition(explode(' ', $string)));

function  partition( $input)
{
    $pivot = $input[0];
    $l = $r = array();
    for ($i = 0; $i < count($input); $i++) {
        if ($input[$i] < $pivot) {
            $l[] = $input[$i];
        } elseif ($input[$i] > $pivot) {
            $r[] = $input[$i];
示例#24
0
<?php

if (!defined('INIT_INSTANCE')) {
    die('Access restricted');
}
$in_use = 0;
$used_archives = array();
$all_news = file($news_file);
if ($reverse == true) {
    $all_news = array_reverse($all_news);
}
if ($orderby == 'R') {
    shuffle($all_news);
} elseif ($orderby) {
    $all_news = quicksort($all_news, $orderby);
}
// Search last comments
if (!empty($sortbylastcom)) {
    $garnews = array();
    foreach ($all_news as $nl) {
        list($id) = explode('|', $nl, 2);
        $garnews[$id] = $nl;
    }
    $all_news = array();
    $all_comments = file($comm_file);
    $all_comments = preg_replace('~^(\\d+)\\|>\\|((\\d+)\\|.*?\\|.*?\\|.*?\\|.*?\\|.*?\\|)*~im', '\\3.\\1', $all_comments);
    arsort($all_comments);
    foreach ($all_comments as $pm) {
        if ($nl = rtrim($garnews[(int) substr($pm, strpos($pm, '.') + 1)])) {
            $all_news[] = $nl;
        }
示例#25
0
 function quicksort($str)
 {
     if (count($str) <= 1) {
         return $str;
     }
     //如果个数不大于一,直接返回
     $key = $str[0];
     //取一个值,稍后用来比较;
     $left_arr = array();
     $right_arr = array();
     for ($i = 1; $i < count($str); $i++) {
         //比$key大的放在右边,小的放在左边;
         if ($str[$i] <= $key) {
             $left_arr[] = $str[$i];
         } else {
             $right_arr[] = $str[$i];
         }
     }
     $left_arr = quicksort($left_arr);
     //进行递归;
     $right_arr = quicksort($right_arr);
     return array_merge($left_arr, array($key), $right_arr);
     //将左中右的值合并成一个数组;
 }
示例#26
0
function quicksort($array, $by = 0)
{
    $bysort = $by;
    list($by, $ord) = explode('/', $by);
    if (count($array) < 2) {
        return $array;
    }
    $left = $right = array();
    reset($array);
    $pivot_key = key($array);
    $pivot = array_shift($array);
    $pivox = explode('|', $pivot);
    foreach ($array as $k => $v) {
        $vx = explode('|', $v);
        if ($ord == 'A' || $ord == 'asc') {
            if ($vx[$by] < $pivox[$by]) {
                $left[$k] = $v;
            } else {
                $right[$k] = $v;
            }
        } else {
            if ($vx[$by] > $pivox[$by]) {
                $left[$k] = $v;
            } else {
                $right[$k] = $v;
            }
        }
    }
    return array_merge(quicksort($left, $bysort), array($pivot_key => $pivot), quicksort($right, $bysort));
}
示例#27
0
     $all_db_tmp[] = $raw_line;
 }
 $all_db = $all_db_tmp;
 // Prelist Entries
 if (empty($start_from)) {
     $start_from = false;
 }
 $ipos = 0;
 $flag = 1;
 $entries_showed = 0;
 // Sort news by...
 if (isset($_REQUEST['ord_title'])) {
     $all_db = quicksort($all_db, NEW_TITLE . '/' . $_REQUEST['ord_title']);
 }
 if (isset($_REQUEST['ord_date'])) {
     $all_db = quicksort($all_db, NEW_ID . '/' . $_REQUEST['ord_date']);
 }
 if (!empty($all_db)) {
     $the_entry = array();
     foreach ($all_db as $line) {
         // Skip $start_from news
         $ipos++;
         if ($ipos < $start_from) {
             continue;
         }
         $item_db = explode("|", $line);
         $itemdate = date("d/m/y", $item_db[0]);
         $bg = $flag ? "#F7F6F4" : "#FFFFFF";
         $flag = 1 - $flag;
         $entry_show = true;
         // Sanitize
示例#28
0
function quicksort (&$array, $first, $last, $key) {
	if ($first < $last) {
		$cmp = $array[floor(($first + $last) / 2)][$key];
		$l = $first;
		$r = $last;
		while ($l <= $r) {
			while ($array[$l][$key] < $cmp) $l++;
			while ($array[$r][$key] > $cmp) $r--;
			if ($l <= $r) {
				$tmp = $array[$l];
				$array[$l] = $array[$r];
				$array[$r] = $tmp;
				$l++;
				$r--;
			}
		}
		quicksort($array, $first, $r, $key);
		quicksort($array, $l, $last, $key);
	}
}
示例#29
0
function quicksort($xs) {

	if($xs->count() < 2)
		return $xs;

	$p = $xs->head();

	$fn = function($x) use($p) { return $x < $p; };

	return
		quicksort($xs->tail()->select($fn))
		->concat(A($p))
		->concat(quicksort($xs->tail()->reject($fn)));
}