search
HomeBackend DevelopmentPHP TutorialPHP Program for Median of two Sorted Arrays of Same Size

PHP Program for Median of two Sorted Arrays of Same Size

PHP (Hypertext Preprocessor) is a popular scripting language designed for web development. It is widely used for creating dynamic and interactive web pages. PHP code can be embedded directly into HTML, allowing developers to mix PHP and HTML seamlessly. PHP can connect to databases, process form data, generate dynamic content, handle file uploads, interact with servers, and perform various server-side tasks.

PHP supports a wide range of web development frameworks, such as Laravel, Symfony, and CodeIgniter, which provide additional tools and features for building web applications. PHP is an open-source language with a large community, extensive documentation, and a rich ecosystem of libraries and extensions.

PHP Program for Median of Two Sorted Arrays of Same Size

The median is a value that separates the higher half from the lower half of the data set. To calculate the median of an array, you need to consider the middle element(s) of the sorted array.

Example

<?php // A Simple Merge based O(n) solution
// to find median of two sorted arrays

// This function returns median of
// ar1[] and ar2[]. Assumptions in
// this function: Both ar1[] and ar2[]
// are sorted arrays Both have n elements
function getMedian($ar1, $ar2, $n)
{
	// Current index of i/p array ar1[]
	$i = 0;

	// Current index of i/p array ar2[]
	$j = 0;
	$count;
	$m1 = -1; $m2 = -1;

	// Since there are 2n elements,
	// median will be average of elements
	// at index n-1 and n in the array
	// obtained after merging ar1 and ar2
	for ($count = 0; $count <= $n; $count++)
	{
		// Below is to handle case where
		// all elements of ar1[] are smaller
		// than smallest(or first) element of ar2[]
		if ($i == $n)
		{
			$m1 = $m2;
			$m2 = $ar2[0];
			break;
		}

		// Below is to handle case where all
		// elements of ar2[] are smaller than
		// smallest(or first) element of ar1[]
		else if ($j == $n)
		{
			$m1 = $m2;
			$m2 = $ar1[0];
			break;
		}

		if ($ar1[$i] < $ar2[$j])
		{
			// Store the prev median
			$m1 = $m2;
			$m2 = $ar1[$i];
			$i++;
		}
		else
		{
			// Store the prev median
			$m1 = $m2;
			$m2 = $ar2[$j];
			$j++;
		}
	}

	return ($m1 + $m2) / 2;
}

// Driver Code
$ar1 = array(1, 3, 5, 7, 9, 11);
$ar2 = array(12, 10 ,8 ,6 ,4, 2);

$n1 = sizeof($ar1);
$n2 = sizeof($ar2);
if ($n1 == $n2)
	echo("Median is " .
		getMedian($ar1, $ar2, $n1));
else
	echo("Doesn't work for arrays".
		"of unequal size");

?>

Output

It will produce the following output:

Median is 11.5

Explanation of code

The provided code implements a simple merge-based solution to find the median of two sorted arrays, $ar1 and $ar2, of the same size. The getMedian function takes the two input arrays and the size n as parameters. It initializes variables to keep track of the current indices, counters, and previous medians. It iterates count from 0 to n, comparing elements from both arrays. It updates the previous and current medians accordingly based on the comparison results.

The function handles cases where one array's elements are smaller than the other array's elements. Finally, it returns the calculated median by averaging the previous and current medians. In the example provided, the driver code creates two arrays, $ar1 and $ar2, and calculates their sizes. It calls the getMedian function to find the median of the arrays and prints the result. If the arrays have unequal sizes, an error message is displayed.

In the example, $ar1 contains [1, 3, 5, 7, 9, 11], and $ar2 contains [12, 10, 8, 6, 4, 2]. Both arrays have the same length, so the algorithm can proceed. The iteration progresses by comparing the elements in the arrays, and the median is updated accordingly. Finally, the median is calculated as (11 + 12) / 2, resulting in a median value of 11.5. Therefore, the output of the code will be "Median is 11.5".

Conclusion

PHP offers a merge-based approach to find the median of two sorted arrays of the same size. By merging the arrays and considering the middle two elements, the program accurately determines the median. It utilizes two indices to traverse the arrays, comparing elements and updating the median variables accordingly.

The resulting median is the average of the middle elements if the array length is even or the middle element if it's odd. This efficient O(n) solution provides a reliable and straightforward method for computing the median of two sorted arrays of the same size in PHP.

The above is the detailed content of PHP Program for Median of two Sorted Arrays of Same Size. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.