So I was going through different sorting algorithms. But almost all the sorting algorithms require 2 loops to sort the array. The time complexity of Bubble sort & Insert
The following code is in PHP to sort an array best case possible. https://paiza.io/projects/r22X0VuHvPQ236jgkataxg
<?php
function quicksort($a){
$n = count($a);
$lt = [];
$gt = [];
if($n < 2){
return $a;
}else{
$f = $a[0];
}
for($i = 1;$i < $n ;$i++){
if($a[$i] > $f){
$gt [] = $a[$i];
}else{
$lt [] = $a[$i];
}
}
return array_merge(quicksort($lt),array($f),quicksort($gt));
}
$ar = [7,4,3,6,5,1,2];
echo "Input array => ".implode(' , ',$ar).'<br>';
$a = quicksort($ar);
echo "Output array => ".implode(' , ',$a);;
?>
static int[] sort(int[] arr){
int idx = 0;
int len = arr.length - 1;
int counter = len;
while(true){
if(idx != len && arr[idx] > arr[idx+1]){
swap(arr, idx, idx + 1);
counter--;
}
idx++;
if(counter == len && idx == len){
break;
}
if(idx == len){
idx = 0;
counter = len;
}
}
return arr;
}
void swap(int[] arr, int i, int j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
The following code is in php. you can test the code on https://paiza.io/projects/4pAp6CuB-e9vhGIblDNCZQ.
$a = [8,3,4,9,1];
for($i=0;$i<count($a)-1;$i++){
if($a[$i] > $a[$i+1]){
$temp = $a[$i];
$a[$i] = $a[$i+1];
$a[$i+1] = $temp;
$i = -1;
}
}
print_r($a);
javascript:
function bruteForce(arr){
for(var i=0;i<arr.length; ){
if(arr[i+1]< arr[i]){
var temp = arr[i];
arr[i]=arr[i+1];
arr[i+1] = temp;
i--;
if(i === -1) i=0;
}else i++;
}
return arr;
}
alert(bruteForce([2,3,4,5,6,23,1,1]));
Copy the code and paste in URL of the browser and hit enter. If the javascript:
is missed then add it.
Here is the code to sort array using only single loop.
var array = [100, 110, 111, 1, 3, 19, 1, 11, -10]
var i = 1
while i < array.count - 1 {
if array[i] > array[i + 1] {
let temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
i = -1;
}
i = i + 1;
}
print(array)
public int find2ndLargest() {
int[] arr = {1,3,14,25,7,20,11,30};
int temp;
// sort array
for (int i=0;i<arr.length-1;i++) {
if (arr[i]>arr[i+1]) {
temp = arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
i=0;
}
}
return arr[arr.length-2];
}