Bubble Sort



Bubble Sort
import java.util.Arrays;
public class BubbleSort{
    public static int[] bubblesort(int[] a){
        for(int i=a.length-1;i>0;i--){
            for(int j=0;j<i;j++){
                if(a[j]>a[j+1]){
                    swap(a,j,j+1);
                }
            }
        }
        return a;
    }
    private static void swap(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i]=arr[j];
        arr[j] = temp;
        
    }
    public static void main(String[] args){
        int[] input = {2,2,435,33,3,3,3,56,6,6,7,8,3,6,9,8,6};
        
        System.out.println("Before: "+Arrays.toString(input));
        int[] output = bubblesort(input);       
        System.out.println("After: "+Arrays.toString(output));      
    }
}
/*
Before: [2, 2, 435, 33, 3, 3, 3, 56, 6, 6, 7, 8, 3, 6, 9, 8, 6]
After: [2, 2, 3, 3, 3, 3, 6, 6, 6, 6, 7, 8, 8, 9, 33, 56, 435]
*/


0 comments:

Post a Comment

Search This Blog

Powered by Blogger.