Function to sort an array of number - php

I want to sort an array given, for example:
"1; -2; 3.5; 4"
But my function doesn't work and if i try var_dump() i only got the numbers unsorted.
Could anyone please help me to understand ?
I put this numbers in example, but if anyone could explain me how to do also if i don't want to put any numbers within my function and to compile directly, for example with that command :
-> php insertion_sort.php "1; -2; 3.5; 4".
Thank you in advance for your help.
function swap($a, $b) {
$tmp;
$tmp = $a;
$a = $b;
$b = $tmp;
}
function insertion_sort($array) {
$array = array(1, -2, 3.5, 4);
$length = count($array);
for ($i = 0; $i < $length; $i++) {
$i_min = $i;
for ($j = $i+1; $j < $length; $j++) {
if ($array[$j] < $array[$i_min]) {
$i_min = $j;
swap($j, $i_min);
}
}
}
}
?>

This if I remember correctly is a bubble sort
function my_sort(&$array)
{
for ($i=0; $i<count($array)-1; $i++){
for ($j=0; ($j<count($array)-$i-1); $j++){
if( $array[$j] > $array[$j+1]) {
// swap
$t = $array[$j];
$array[$j] = $array[$j+1];
$array[$j+1] = $t;
}
}
}
}
$array = [1,4, -2, 3.5];
my_sort($array);
print_r($array);

Related

php function to sort arrays manually without using automatic sorting

How to sort an array with a function manually in alphabetical order?
Without using automatic sort such as (sort, asort, usort, ...)
I've tried the code below so far but I feel like there is another way to do it
<?php
function sort_arrays(array $var) {
for ($i=0; $i < 4; $i++) {
print_r($var);
}
else {
return null;
}
}
sort_arrays($array = array("A_first","D_last","B_second","C_third"));
// take an array with some elements
$array = array('a','z','c','b');
// get the size of array
$count = count($array);
echo "<pre>";
// Print array elements before sorting
print_r($array);
for ($i = 0; $i < $count; $i++) {
for ($j = $i + 1; $j < $count; $j++) {
if ($array[$i] > $array[$j]) {
$temp = $array[$i];
$array[$i] = $array[$j];
$array[$j] = $temp;
}
}
}
echo "Sorted Array:" . "<br/>";
print_r($array);
$arr = ['c','a','d','b'];
$size =count($arr);
for($i=0; $i<$size; $i++){
/*
* Place currently selected element array[i]
* to its correct place.
*/
for($j=$i+1; $j<$size; $j++)
{
/*
* Swap if currently selected array element
* is not at its correct position.
*/
if($arr[$i] > $arr[$j])
{
$temp = $arr[$i];
$arr[$i] = $arr[$j];
$arr[$j] = $temp;
}
}
}
print_r($arr);
$arr = array('Apple', 'Banana', 'Chips', 'Dr.Pepper'); // Create a sorted array manually
print_r($arr); // prints a manually sorted array

Gaussian elimination has to give back multiple solutions php

I want to use gaussian elimination to solve the following matrix Matrix and this is the answer I'm expecting. I would like to get back an equation in the form as is displayed in answer but i can't figure out how to do it.
public function gauss($A, $x) {
# Just make a single matrix
for ($i=0; $i < count($A); $i++) {
$A[$i][] = $x[$i];
}
$n = count($A);
for ($i=0; $i < $n; $i++) {
# Search for maximum in this column
$maxEl = abs($A[$i][$i]);
$maxRow = $i;
for ($k=$i+1; $k < $n; $k++) {
if (abs($A[$k][$i]) > $maxEl) {
$maxEl = abs($A[$k][$i]);
$maxRow = $k;
}
}
# Swap maximum row with current row (column by column)
for ($k=$i; $k < $n+1; $k++) {
$tmp = $A[$maxRow][$k];
$A[$maxRow][$k] = $A[$i][$k];
$A[$i][$k] = $tmp;
}
# Make all rows below this one 0 in current column
for ($k=$i+1; $k < $n; $k++) {
$c = -$A[$k][$i]/$A[$i][$i];
for ($j=$i; $j < $n+1; $j++) {
if ($i==$j) {
$A[$k][$j] = 0;
} else {
$A[$k][$j] += $c * $A[$i][$j];
}
}
}
}
# Solve equation Ax=b for an upper triangular matrix $A
$x = array_fill(0, $n, 0);
for ($i=$n-1; $i > -1; $i--) {
$x[$i] = $A[$i][$n]/$A[$i][$i];
for ($k=$i-1; $k > -1; $k--) {
$A[$k][$n] -= $A[$k][$i] * $x[$i];
}
}
return $x;
}
I hope someone can help me to rewrite this code so it gives the solution i've provided or recommend a library which is capable of doing this.
I've searched for possible solutions on Google but haven't been able to find one yet.
Thanks in advance.

Bubble Sort in PHP and Python

As far as I can tell, these two programs should do exactly the same thing. However, the Python version works and the PHP one doesn't. What am I missing please?
def bubbleSort(alist):
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
my_list = [2,3,5,4,1]
bubbleSort(my_list)
print(my_list)
<?php
// Bubble Sort
$my_list = [2,3,5,4,1];
function bubble_sort($arr){
$size = count($arr);
for($pass_num = $size - 1; $pass_num >= 0; $pass_num--){
for($i = 0; $i < $pass_num; $i++){
if($arr[i] > $arr[$i + 1]){
swap($arr, $arr[i], $arr[$i+1]);
}
}
}
}
function swap(&$arr, $a, $b) {
$tmp = $arr[$a];
$arr[$a] = $arr[$b];
$arr[$b] = $tmp;
}
bubble_sort($my_list);
print_r ($my_list);
The sort is in fact working, but as you dont pass a reference to the bubble_sort($arr) function you never get to see the actual result. Telling bubble_sort() that the array is being passed by reference means you are changing $my_list and not a copy of $my_list
Oh and you had some compile errors, using $arr[i] instead of $arr[$i]
// Bubble Sort
$my_list = [2,3,5,4,1];
function bubble_sort(&$arr){ // <-- changed to &$arr
$size = count($arr);
for($pass_num = $size - 1; $pass_num >= 0; $pass_num--){
for($i = 0; $i < $pass_num; $i++){
if($arr[$i] > $arr[$i + 1]){
// also changed this line to pass just the indexes
swap($arr, $i, $i+1);
}
}
}
}
function swap(&$arr, $a, $b) {
$tmp = $arr[$a];
$arr[$a] = $arr[$b];
$arr[$b] = $tmp;
}
bubble_sort($my_list);
print_r ($my_list);
If you are testing this on a live server where error reporting is turned off add these lines to the top of any script you are developing, while you are developing it.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
And the compile errors would have shown on the web page
Bubble Sort Php
$data_set = [3,44,38,5,15,26,27,2,46,4];
function bubble_sort($data_set){
$number_of_items = count($data_set);
for($i = 0; $i <= $number_of_items - 2; $i++){
for($j = 0; $j <= $number_of_items -($i+2); $j++){
if($data_set[$j] > $data_set[$j + 1]){
$temp = $data_set[$j];
$data_set[$j] = $data_set[$j + 1];
$data_set[$j + 1] = $temp;
}
}
}
return $data_set;
}
echo '<pre>';
print_r(bubble_sort($data_set));
echo '</pre>';

How to find duplicate values in an array without using array_count_values

I am trying to find duplicated values/string in an array using for loop
<?php
$b=array('a','b','c','a','b');
$c=count($b);
$d=array();
for($i=0;$i<=($c-1);$i++)
{
for($j=1;$j<=($c-1);$j++)
{
if($b[$i]!=$b[$j])
{
$flag=1;
}
}
if($flag==1)
{
$d[$i]=$b[$i];
}
}
print_R($d);
?>
where is my mistake? I have used array $d to display non duplicate values.....
NOTE: I need to try this only with for loop - I know how to do it using array functions.
You should reverse your test, because there are almost always values, which are different from the one you're testing. And you must reset your $flag before the inner loop, otherwise it will always be true.
When you want to find unique values, you can just test against $d only. If the value is already in $d, skip it.
$c1 = count($b);
for ($i = 0; $i < $c1; $i++) {
$dup = 0;
$c2 = count($d);
for ($j = 0; $j < $c2; $j++) {
if ($b[$i] == $d[$j])
$dup = 1;
}
if (!$dup)
$d[] = $b[$i];
}
print_r($d);
If you want to find values, which don't have duplicates instead
for ($i = 0; $i < $c; $i++) {
$dup = 0;
for ($j = 0; $j < $c; $j++) {
if ($i != $j && $b[$i] == $b[$j])
$dup = 1;
}
if (!$dup)
$d[] = $b[$i];
}
function has_dupes($array){
$dupe = array();
foreach($array as $val){
if(++$dupe[$val] > 1)
return true;
}
return false;
}
could do something like this.. this would check for dupes, then u can print the uniques
Why are you making a simple task complex .. simply
$b = array('a','b','c','a','b');
var_dump(customCount($b));
Output
array (size=3)
'a' => int 2 //duplicate
'b' => int 2 //duplicate
'c' => int 1
Function Used
function customCount($array) {
$temp = array();
foreach ( $array as $v ) {
isset($temp[$v]) or $temp[$v] = 0;
$temp[$v] ++;
}
return $temp ;
}

Bubble sort implementation in PHP? [duplicate]

This question already has answers here:
How can I sort arrays and data in PHP?
(14 answers)
Closed 7 years ago.
I need to do a bubble sort algorithm in PHP.
I want to know whether any one has any good examples that I can use, or an open source library which can do this.
I have a few spaces in a set (array), i want to fill these spaces with object (a person), so no space can have a male and a female, this why i am trying to find out a bubble sort algorithm.
My plan is to fill in any of the available spaces regardless of the gender, and after that sort them separately.
Thanks.
function bubble_sort($arr) {
$size = count($arr)-1;
for ($i=0; $i<$size; $i++) {
for ($j=0; $j<$size-$i; $j++) {
$k = $j+1;
if ($arr[$k] < $arr[$j]) {
// Swap elements at indices: $j, $k
list($arr[$j], $arr[$k]) = array($arr[$k], $arr[$j]);
}
}
}
return $arr;
}
For example:
$arr = array(1,3,2,8,5,7,4,0);
print("Before sorting");
print_r($arr);
$arr = bubble_sort($arr);
print("After sorting by using bubble sort");
print_r($arr);
Using bubble sort is a very bad idea. It has complexity of O(n^2).
You should use php usort, which is actually a merge sort implementation and guaranteed O(n*log(n)) complexity.
A sample code from the PHP Manual -
function cmp( $a, $b ) {
if( $a->weight == $b->weight ){ return 0 ; }
return ($a->weight < $b->weight) ? -1 : 1;
}
usort($unsortedObjectArray,'cmp');
$numbers = array(1,3,2,5,2);
$array_size = count($numbers);
echo "Numbers before sort: ";
for ( $i = 0; $i < $array_size; $i++ )
echo $numbers[$i];
echo "n";
for ( $i = 0; $i < $array_size; $i++ )
{
for ($j = 0; $j < $array_size; $j++ )
{
if ($numbers[$i] < $numbers[$j])
{
$temp = $numbers[$i];
$numbers[$i] = $numbers[$j];
$numbers[$j] = $temp;
}
}
}
echo "Numbers after sort: ";
for( $i = 0; $i < $array_size; $i++ )
echo $numbers[$i];
echo "n";
function bubble_sort($arr) {
$n = count($arr);
do {
$swapped = false;
for ($i = 0; $i < $n - 1; $i++) {
// swap when out of order
if ($arr[$i] > $arr[$i + 1]) {
$temp = $arr[$i];
$arr[$i] = $arr[$i + 1];
$arr[$i + 1] = $temp;
$swapped = true;
}
}
$n--;
}
while ($swapped);
return $arr;
}
function bubbleSort(array $arr)
{
$n = sizeof($arr);
for ($i = 1; $i < $n; $i++) {
for ($j = $n - 1; $j >= $i; $j--) {
if($arr[$j-1] > $arr[$j]) {
$tmp = $arr[$j - 1];
$arr[$j - 1] = $arr[$j];
$arr[$j] = $tmp;
}
}
}
return $arr;
}
// Example:
$arr = array(255,1,22,3,45,5);
$result = bubbleSort($arr);
print_r($result);
//====================================================
//------- improved version----------------------------
//====================================================
function bubbleSortImproved(array $arr)
{
$n = sizeof($arr);
for ($i = 1; $i < $n; $i++) {
$flag = false;
for ($j = $n - 1; $j >= $i; $j--) {
if($arr[$j-1] > $arr[$j]) {
$tmp = $arr[$j - 1];
$arr[$j - 1] = $arr[$j];
$arr[$j] = $tmp;
$flag = true;
}
}
if (!$flag) {
break;
}
}
return $arr;
}
// Example:
$arr = array(255,1,22,3,45,5);
$result = bubbleSortImproved($arr);
print_r($result);
Improved Bubble Sorting enjoy :)
$sortarr = array(3,5,15,3,2,6,7,50,1,4,5,2,100,9,3,2,6,7,13,18);
echo "<pre>";
// Array to be sorted
print_r($sortarr);
// Sorted Array
print_r(bubble_sort($sortarr));
echo "<pre>";
function bubble_sort($sortarr){
// Bubble sorting
$array_count = count($sortarr);
for($x = 0; $x < $array_count; $x++){
for($a = 0 ; $a < $array_count - 1 ; $a++){
if($a < $array_count ){
if($sortarr[$a] > $sortarr[$a + 1] ){
swap($sortarr, $a, $a+1);
}
}
}
}
return $sortarr;
}
function swap(&$arr, $a, $b) {
$tmp = $arr[$a];
$arr[$a] = $arr[$b];
$arr[$b] = $tmp;
}
Maybe someone finds useful my version of Bubble Sort:
function BubbleSort(&$L)
{
$rm_key = count($L);
while( --$rm_key > -1 )#after this the very first time it will point to the last element
for($i=0; $i<$rm_key; $i++)
if( $L[$i] > $L[$i+1] )
list($L[$i],$L[$i+1]) = array($L[$i+1],$L[$i]);
}
I got the swap idea (using list) from above comment.

Categories