DEV Community

Guna Sekaran
Guna Sekaran

Posted on

Bubble Sorting & Selection Sorting In Java

package array;

                                 BUBBLE SORTING:                            


public class Bubble_sort {
    public static void main(String[] args) {
         int[] ar = {50, 40, 30, 20, 10};
            for(int j = 1; j < ar.length; j++ ) {
              for(int i = 0; i < ar.length - j; i++) {
                if(ar[i] > ar[i+1]) {
                  int temp = ar[i];
                  ar[i] = ar[i+1];
                  ar[i+1] = temp;
                }
              }
            }
            for(int i = 0; i < ar.length; i++ )
              System.out.print(ar[i]+" ");


    }

}

.........................................................................

OUTPUT:
10 20 30 40 50 
Enter fullscreen mode Exit fullscreen mode
                                SELECTION SORTING:                      

package array;

public class Selection_sort {
    public static void main(String[] args) {
        int[] ar = {9,8,7,6,5,4,3,2,1};
        for(int j = 0; j < ar.length - 1; j++) {
          int big = 0;
          int big_index = 0;
          for(int i = 0; i < ar.length - j; i++) {
            if(ar[i] > big) {
              big_index = i;
              big = ar[i];
            }
          }

          int len = ar.length - (j + 1);
          int temp = ar[len];
          ar[len] = big;
          ar[big_index] = temp;
        }
        for(int i = 0; i < ar.length; i++) {
          System.out.print(ar[i]+" ");
        }




    }

}

.........................................................................

OUTPUT:

1 2 3 4 5 6 7 8 9 10 

Enter fullscreen mode Exit fullscreen mode
                               LINEAR SEARCHING:

package array;

public class Linear_searching {
    public static void main(String[] args) {
        int[]array= {5,8,11,22,24,31,48,88};
        int selected_num=22;
        for(int i=0;i<array.length;i++) {

            if(array[i]==selected_num) {

                System.out.println(selected_num+" "+"is presented in list");


            }

    }

    }
}

.........................................................................

OUTPUT:

22 is presented in list


Enter fullscreen mode Exit fullscreen mode

Top comments (0)