Website For Developers

Sorting in Java



Selection Sort in Java


Example of selection sort in Java

public class SelectionSort {

   public static void main(String args[]) {
      int[] array = {4, 3, 5, 2, 1};
      int min,temp;
      System.out.println( "Before Sorting:" );

      //before sorting
      for (int i=0; i<array.length; i++) {
         System.out.print(array[i]+" ");
      }

      //sorting...
      for (int i=0; i<array.length-1; i++) {
         min = i;
         for (int j=0; j<array.length; j++) {
            if (array[j] < array[i]) {
               min = j;
            }
            if (min != i) {

              //swapping
              temp = array[i];
              array[i] = array[min];
              array[min] = temp;
            }
         }
      }
      System.out.println( "\nAfter Sorting:" );

      //Array printing after sort
      for (int i = 0; i<array.length; i++) {
         System.out.print(array[i]+" ");
      }
   }
}

Output

Before Sorting:
4 3 5 2 1
After Sorting:
1 2 4 3 5

Explanation of the above example

Bubble Sort in Java

Example of bubble sort in Java

public class BubbleSort {

   public static void main(String args[]) {
     int[] array = {33, 55, 22, 11, 44};
     int temp;
     System.out.println( "Before Sorting:" );
     //before sorting
     for (int i = 0; i < array.length; i++) {
       System.out.print(array[i]+" ");
     }
     //sorting...
     for (int i = 0; i < array.length; i++) {
       for (int j = 0; j < array.length-1; j++) {
         //swapping
         if (array[j]>array[j+1]) {
           temp = array[j];
           array[j] = array[j+1];
           array[j+1] = temp;
         }
       }
     }
     System.out.println( "\nAfter Sorting:" );
     //after sorting
     for (int i = 0; i < array.length; i++) {
       System.out.print(array[i]+" ");
     }
   }
}

Output

Before Sorting:
33 55 22 11 44
After Sorting:
11 22 33 44 55