Bubble Sort program


class BubbleSort {
    private static int[] array;
    
    private void sort() {
        boolean sorted = true;
        for(int i = 0; i < array.length; i++) {
            for(int j = 1; j < array.length - i; j++) {
                if(array[j] < array[j-1]) {
                    swap(j, j-1);
                    sorted = false;
                }
            }
            if(sorted) {
                break;
            }
        }
    }
    
    private void swap(int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    
    private void display() {
        for(int key : array) {
            System.out.print(key + " ");
        }
    }
    
	public static void main (String[] args) {
	    BubbleSort obj = new BubbleSort();
		array = new int[] {11,13,7,12,16,9,24,5,10,3};
		System.out.println("Unsorted array : ");
		obj.display();
		
		obj.sort();
		System.out.println("\nSorted array : ");
		obj.display();
	}
}


Output
Unsorted array : 
11 13 7 12 16 9 24 5 10 3 
Sorted array : 
3 5 7 9 10 11 12 13 16 24 

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance