How to sort an array without using sort method in java

Let’s learn how to sort an array without using sort method in java.

How to sort an array without using sort method in java

In the below program on how to sort an array without using sort method we are not using Arrays.sort() method to sort given array.

Meanwhile we are sorting array elements in both ascending and descending order without using Arrays sort method. Here’s program on how to sort an array without using sort method in descending order.

// descending order
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);
      }
   }
}

Output:

Before sort:
14
8
5
54
41
10
1
500
After sort:
500
54
41
14
10
8
5
1


Now let’s see how to sort an array without using Arrays.sort() method in ascending order.

public class WithoutSortMethod
{
   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; a++)
      {
         for(int b = a + 1; b < arrNumbers.length; b++)
         {
            if(arrNumbers[a] > arrNumbers[b])
            {
               temp = arrNumbers[a];
               arrNumbers[a] = arrNumbers[b];
               arrNumbers[b] = temp;
            }
         }
      }
      System.out.println("After sort: ");
      for(int num : arrNumbers)
      {
         System.out.println(num);
      }
   }
}

Output:

Before sort:
14
8
5
54
41
10
1
500
After sort:
1
5
8
10
14
41
54
500


Also read – multidimensional array in java