Sunday, October 29, 2017

Day 4 - Bubble Sort

Bubble Sort - This is a simple sorting algorithm where elements of an array are swapped until sorting is achieved. It is a very inefficient algorithm. The basic theory behind bubble sorting is take an array of size n; iterate over the list; for each element at index i, if it greater than the element at next index (i+1), swap them. This causes the greater elements to go to the back of the array.

Implementation:
public class BubbleSort {

public static void main(String[] args) {
Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] a = new int[n];
        for(int a_i=0; a_i < n; a_i++){
            a[a_i] = in.nextInt();
        }
        int swap = 0;
        for(int i=0;i
        for(int j=i+1;j
        if(a[i]>a[j]){
        int temp = a[i];
        a[i] = a[j];
        a[j] = temp;
        swap ++;
        }
        }
        }
        
        System.out.println("Array is sorted in "+swap+" swaps.");
        System.out.println("First element: "+a[0]);
        System.out.println("Last element: "+a[n-1]);

}

}
 Input: 
3
3 2 1

Output:
Array is sorted in 0 swaps.
First element: 1
Last element: 3

No comments: