Bubble sort Java

5:49 PM

Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list. Because it only uses comparisons to operate on elements, it is a comparison sort. Although the algorithm is simple, most of the other sorting algorithms are more efficient for large lists.(wikipedia)
 import java.util.*;
public class BubbleSort {
    public static void main(String[] args){
        System.out.println("input array size");
        int n=input();
      
        int data[]=new int[n];
        System.out.println("input array value");
        for(int i=0;i<data.length;i++){
            data[i]=input();
        }
        urutkanBubble(data.length, data);
        System.out.print("hasil akhir : ");
        show(data.length,data);
    }
    static void show(int n,int[] data){
        for(int i=0;i<n;i++){
            System.out.print(data[i]+" ");
        }
      
    }
    static void urutkanBubble(int n,int[] data){
        for(int i=1;i<n;i++){
            for(int j=0;j<n-i;j++){
                if(data[j]>data[j+1]){
                    int tmp=data[j];
                    data[j]=data[j+1];
                    data[j+1]=tmp;
                }                             
            }System.out.print("Hasil pada tahap ke-"+i+" :");
            show(n,data);
            System.out.println("");
        } 
    }
    static int input(){
        Scanner a=new Scanner(System.in);
        int b=a.nextInt();
        return b;
    }
}

You Might Also Like

0 comments