Pages

Monday, June 29, 2015

Bubble Sort

How its work?
An example of bubble sort. Starting from the beginning of the list, compare every adjacent pair, swap their position if they are not in the right order (the latter one is smaller than the former one). After each iteration, one less element (the last one) is needed to be compared until there are no more elements left to be compared.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class BubbleSort {
        public static void main(String[] args) {
                int intArray[] = new int[]{51,1,61,7,55,90,25,99,91,15,35};
               
                System.out.println("Array Before Bubble Sort");
                for(int i=0; i < intArray.length; i++){
                        System.out.print(intArray[i] + ", ");
                }
                System.out.println();
                bubbleSort(intArray);
        }
 
        private static void bubbleSort(int[] intArray) {
           int n = intArray.length;
           int temp = 0;
           for(int i=0; i < n; i++){
               for(int j=1; j < (n-i); j++){
                  if(intArray[j-1] > intArray[j]){
                     temp = intArray[j-1];
                     intArray[j-1] = intArray[j];
                     intArray[j] = temp;             
                   }      
                   display(intArray);
                }
           }
        }
        
        private static void display(int[] intArray){
            for(int i=0; i < intArray.length; i++){
                    System.out.print(intArray[i] + ", ");
                }
                System.out.println();
        }
}

No comments:

Post a Comment