write sort without srot in php

can help with that. Sorting an array without using PHP's built-in sorting functions involves implementing a sorting algorithm manually. One of the simplest sorting algorithms is the Bubble Sort algorithm. Here's an example of how you can sort a single-dimensional indexed array containing integers without using PHP's sorting functions:

php
<?php function bubbleSort(&$arr) { $n = count($arr); for ($i = 0; $i < $n - 1; $i++) { // Last $i elements are already in place for ($j = 0; $j < $n - $i - 1; $j++) { if ($arr[$j] > $arr[$j + 1]) { // Swap elements if they are in the wrong order $temp = $arr[$j]; $arr[$j] = $arr[$j + 1]; $arr[$j + 1] = $temp; } } } } // Sample array $array = [5, 3, 8, 1, 9, 2]; // Sort the array using bubble sort bubbleSort($array); // Print the sorted array foreach ($array as $value) { echo $value . " "; } ?>

This program defines a function bubbleSort that implements the Bubble Sort algorithm. It then uses this function to sort the given array. The sorted array is printed using a loop.

Keep in mind that Bubble Sort is not the most efficient sorting algorithm for large arrays, as it has a time complexity of O(n^2). However, it's suitable for educational purposes and small arrays. For larger arrays, you might consider more efficient sorting algorithms like Quick Sort or Merge Sort.

No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...