PHPBuilder - ShellSort Function



RSS Twitter
Snippets Algorithms

ShellSort Function

by: jayon crow
|
March 22, 2007

Version: 1.0

Type: Function

Category: Algorithms

License: GNU General Public License

Description: This is one of best sorting algorithm that use for sorting quickly . it's order is sqr(n)



/* Author: Masuod Maldar, masuod_maldar@yahoo.com
 * UpdatedBy: J.B.Lamer, Date: 20070322
 *
 * It's like a binary bubble sort and is more consistant than quicksort
 *   and it's fast without creating other arrays or bins
 *
 * $array_to_sort is the array that needs sorting
 *   the keys are pulled and replaced with a normal numeric array
 * false is returned if $array_to_sort is not an array
 *   and true is returned otherwise
 */
function shellsort( &$array_to_sort )
{
	if ( !is_array($array_to_sort) )
	{	return false; }
	
	$array_to_sort = array_values($array_to_sort);
	
	$len = count($array_to_sort);
	$k = 0;
	$gap[0] = floor( $len / 2 );
	while ( $gap[$k] > 1 )
	{
		$k++;
		$gap[$k] = floor($gap[$k-1]/2);
	}
	
	for ( $i=0; $i <= $k; $i++ )
	{
		$step = $gap[$i];
		for ( $j = $step; $j < $len; $j++ )
		{
			$temp = $array_to_sort[$j];
			$p = $j - $step;
			while ( $p >= 0 && $temp < $array_to_sort[$p] )
			{
				$array_to_sort[$p+$step] = $array_to_sort[$p];
				$p -= $step;
			}
			$array_to_sort[$p+$step] = $temp;
		}
	}
	return true;
}

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
jayon crow

Comment:



Comment:

(Maximum characters: 1200). You have characters left.