# PHP Searching and Sorting Algorithm - Exercises, Practice, Solution

## PHP Searching and Sorting Algorithm [17 exercises with solution]

[An editor is available at the bottom of the page to write and execute the scripts.]

1. Write a PHP program to sort a list of elements using Quick sort.Go to the editor
Quick sort is a comparison sort, meaning that it can sort items of any type for which a "less-than" relation (formally, a total order) is defined.
Click me to see the solution

2. Write a PHP program to sort a list of elements using Heap sort. Go to the editor
In computer science, heapsort (invented by J. W. J. Williams in 1964) is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it interactively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but it is not a stable sort.
A run of the heapsort algorithm sorting an array of randomly permuted values. In the first stage of the algorithm, the array elements are reordered to satisfy the heap property. Before the actual sorting takes place, the heap tree structure is shown briefly for illustration.
Click me to see the solution

3. Write a PHP program to sort a list of elements using Insertion sort. Go to the editor
Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
Click me to see the solution

4. Write a PHP program to sort a list of elements using Selection sort. Go to the editor
The selection sort improves on the bubble sort by making only one exchange for every pass through the list.
Click me to see the solution

5. Write a PHP program to sort a list of elements using Shell sort. Go to the editor
According to Wikipedia "Shell sort or Shell's method, is an in-place comparison sort. It can be seen as either a generalization of sorting by exchange (bubble sort) or sorting by insertion (insertion sort). The method starts by sorting pairs of elements far apart from each other, then progressively reducing the gap between elements to be compared. Starting with far apart elements can move some out-of-place elements into position faster than a simple nearest neighbor exchange."
Click me to see the solution

6. Write a PHP program to sort a list of elements using Bubble sort. Go to the editor
According to Wikipedia "Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sort order but may occasionally have some out-of-order elements nearly in position."
Click me to see the solution

7. Write a PHP program to sort a list of elements using Cocktail sort. Go to the editor
Cocktail shaker sort (also known as bidirectional bubble sort, cocktail sort, shaker sort, ripple sort, shuffle sort, or shuttle sort ) is a variation of bubble sort that is both a stable sorting algorithm and a comparison sort. The algorithm differs from a bubble sort in that it sorts in both directions on each pass through the list. This sorting algorithm is only marginally more difficult to implement than a bubble sort and solves the problem of turtles in bubble sorts. It provides only marginal performance improvements, and does not improve asymptotic performance; like the bubble sort, it is not of practical interest, though it finds some use in education.
Click me to see the solution

8. Write a PHP program to sort a list of elements using Comb sort. Go to the editor
The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Some implementations use the insertion sort once the gap is less than a certain amount. The basic idea is to eliminate turtles, or small values near the end of the list since in a bubble sort these slow the sorting down tremendously. Rabbits, large values around the beginning of the list, do not pose a problem in bubble sort.
In bubble sort, when any two elements are compared, they always have a gap of 1. The basic idea of comb sort is that the gap can be much more than 1.
Click me to see the solution

9. Write a PHP program to sort a list of elements using Gnome sort. Go to the editor
Gnome sort is a sorting algorithm originally proposed by Dr. Hamid Sarbazi-Azad (Professor of Computer Engineering at Sharif University of Technology) in 2000 and called "stupid sort" (not to be confused with bogosort), and then later on described by Dick Grune and named "gnome sort".
The algorithm always finds the first place where two adjacent elements are in the wrong order and swaps them. It takes advantage of the fact that performing a swap can introduce a new out-of-order adjacent pair only next to the two swapped elements.
Click me to see the solution

10. Write a PHP program to sort a list of elements using Bucket sort. Go to the editor
Click me to see the solution

11. Write a PHP program to sort a list of elements using Counting sort. Go to the editor
According to Wikipedia "In computer science, counting sort is an algorithm for sorting a collection of objects according to keys that are small integers; that is, it is an integer sorting algorithm. It operates by counting the number of objects that have each distinct key value, and using arithmetic on those counts to determine the positions of each key value in the output sequence. Its running time is linear in the number of items and the difference between the maximum and minimum key values, so it is only suitable for direct use in situations where the variation in keys is not significantly greater than the number of items. However, it is often used as a subroutine in another sorting algorithm, radix sort, that can handle larger keys more efficiently".
The algorithm loops over the items, computing a histogram of the number of times each key occurs within the input collection. It then performs a prefix sum computation (a second loop, over the range of possible keys) to determine, for each key, the starting position in the output array of the items having that key. Finally, it loops over the items again, moving each item into its sorted position in the output array.
Click me to see the solution

12. Write a PHP program to sort a list of elements using Radix sort. Go to the editor
Click me to see the solution

13. Write a PHP program to sort a list of elements using Bead sort.Go to the editor
Click me to see the solution

14. Write a PHP program to sort a list of elements using Bogo sort. Go to the editor
In computer science, bogosort is a particularly ineffective sorting algorithm based on the generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorted. It is not useful for sorting but may be used for educational purposes, to contrast it with other more realistic algorithms.
Click me to see the solution

15. Write a PHP program to sort a list of elements using Strand sort. Go to the editor
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
Click me to see the solution

16. Write a PHP program to sort a list of elements using Patience sort. Go to the editor
Patience sorting is a sorting algorithm inspired by and named after, the card game patience. A variant of the algorithm efficiently computes the length of a longest increasing subsequence in a given array.
The algorithm's name derives from a simplified variant of the patience card game. This game begins with a shuffled deck of cards. These cards are dealt one by one into a sequence of piles on the table, according to the following rules.

• Initially, there are no piles. The first card dealt forms a new pile consisting of the single card.
• Each subsequent card is placed on the leftmost existing pile whose top card has a value greater than or equal the new card's value, or to the right of all of the existing piles, thus forming a new pile.
• When there are no more cards remaining to deal, the game ends.

This card game is turned into a two-phase sorting algorithm, as follows. Given an array of n elements from some totally ordered domain, consider this array as a collection of cards and simulate the patience sorting game. When the game is over, recover the sorted sequence by repeatedly picking off the minimum visible card; in order words, perform an p-way merge of the p piles, each of which is internally sorted.

Click me to see the solution

17. Write a PHP program to sort a list of elements using Merge sort.Go to the editor
According to Wikipedia "Merge sort (also commonly spelled mergesort) is an O (n log n) comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output."
Click me to see the solution

More to Come !

PHP Code Editor:

More to Come !

Do not submit any solution of the above exercises at here, if you want to contribute go to the appropriate exercise page.

﻿

## PHP: Tips of the Day

Members of objects or classes can be accessed using the object operator (->) and the class operator (::).

Example:

```class MyClass {
public \$a = 1;
public static \$b = 2;
const C = 3;
public function d() { return 4; }
public static function e() { return 5; }
}
\$object = new MyClass();
var_dump(\$object->a); // int(1)
var_dump(\$object::\$b); // int(2)
var_dump(\$object::C); // int(3)
var_dump(MyClass::\$b); // int(2)
var_dump(MyClass::C); // int(3)
var_dump(\$object->d()); // int(4)
var_dump(\$object::d()); // int(4)
var_dump(MyClass::e()); // int(5)
\$classname = "MyClass";
var_dump(\$classname::e()); // also works! int(5)
```

Note that after the object operator, the \$ should not be written (\$object->a instead of \$object->\$a). For the class operator, this is not the case and the \$ is necessary. For a constant defined in the class, the \$ is never used.

Also note that var_dump(MyClass::d()); is only allowed if the function d() does not reference the object:

```class MyClass {
private \$a = 1;
public function d() {
return \$this->a;
}
}
\$object = new MyClass();
var_dump(MyClass::d()); // Error!
```

This causes a 'PHP Fatal error: Uncaught Error: Using \$this when not in object context'

These operators have left associativity, which can be used for 'chaining':

```class MyClass {
private \$a = 1;

\$this->a += \$a;
return \$this;
}

public function get() {
return \$this->a;
}
}
\$object = new MyClass();
```

These operators have the highest precedence (they are not even mentioned in the manual), even higher that clone. Thus:

```class MyClass {
private \$a = 0;
\$this->a += \$a;
return \$this;
}
public function get() {
return \$this->a;
}
}
\$o1 = new MyClass();
var_dump(\$o1->get()); // int(2)
var_dump(\$o2->get()); // int(2)
```

The value of \$o1 is added to before the object is cloned!

Note that using parentheses to influence precedence did not work in PHP version 5 and older (it does in PHP 7):

```// using the class MyClass from the previous code
\$o1 = new MyClass();
\$o2 = (clone \$o1)->add(2); // Error in PHP 5 and before, fine in PHP 7
var_dump(\$o1->get()); // int(0) in PHP 7
var_dump(\$o2->get()); // int(2) in PHP 7
```