Labels

Monday 7 September 2015

Bubble Sort Algorithm

Bubble Sort algorithm is a sorting technique in which we choose the smallest element from the array and keep that element at first position, then we choose the next smallest element in remaining part of array, we keep that at 2nd position, then we choose next element for 3rd position and we continue these steps till the last element, and finally we will have a sorted Array.

Average Case Complexity : O(n^2)
Worst Case Complexity : O(n^2)

Basic Idea : 

For every position in array starting with 0th position, find the smallest element in list (from current position to end), and place the element at the current position, continue this till end of array is reached.



Java Code : 

package Sorting;

public class BubbleSort {
      // method to be called to Apply sort, method returns a sorted array
            public static int[] Sort(int[] array){
                  //for every element from 0 to length-1
                  for(int i = 0; i<array.length; i++){
                        int minIndex = i;
                        //find min value element in array from position i to length-1
                        for(int j=i+1; j<array.length; j++){
                              if(array[j] < array[minIndex]){
                                    minIndex = j;
                              }
                        }
                        //if min value element is not at position i
                        //swap the min value element with the element at i
                        if(minIndex!=i){
                              int temp = array[minIndex];
                              array[minIndex] = array[i];
                              array[i] = temp;
                        }
                  }// end for loop
                  return array;
            }// end sort method

}

No comments:

Post a Comment