how to sort an array without methods code example
Example 1: How to sort an array without using sort method in java
public class WithoutUsingSortMethod
{
public static void main(String[] args)
{
int temp;
int[] arrNumbers = {14, 8, 5, 54, 41, 10, 1, 500};
System.out.println("Before sort: ");
for(int num : arrNumbers)
{
System.out.println(num);
}
for(int a = 0; a <= arrNumbers.length - 1; a++)
{
for(int b = 0; b <= arrNumbers.length - 2; b++)
{
if(arrNumbers[b] < arrNumbers[b + 1])
{
temp = arrNumbers[b];
arrNumbers[b] = arrNumbers[b + 1];
arrNumbers[b + 1] = temp;
}
}
}
System.out.println("After sort: ");
for(int num : arrNumbers)
{
System.out.println(num);
}
}
}
Example 2: how to sort array without using sort method in javascript
function bubbleSort(array) {
var done = false;
while (!done) {
done = true;
for (var i = 1; i < array.length; i += 1) {
if (array[i - 1] > array[i]) {
done = false;
var tmp = array[i - 1];
array[i - 1] = array[i];
array[i] = tmp;
}
}
}
return array;
}
var numbers = [12, 10, 15, 11, 14, 13, 16];
bubbleSort(numbers);
console.log(numbers);