Bubble sort is one of the simplest and easiest of sorting algorithms available. But bubble sort is has almost no practical usage because it is inefficient to sort large volumes of data. Then again bubble sort is good easy solution for simple low volumes of data.
Process
- Lets say we want an array of ascending order. Meaning largest element in the right corner.
- First take first element. That is [in] th element according to the figure above.
- Then compare[in] and [in + 1] th element.
- If in > in+1, we have swap these two. Because we want to move the largest element of this array to the right hand corner.
- We have to do this untill, in=0 to in<out. When this first pass is over, largest element is on out.
- So now we have to take care of the array, starting from in=0 to out-1.
- So in each pass next largest value goes to right hand corner and out decrements by 1.
- When out reaches 1, that means the array is sorted.
/* * Bubble sort implementation * * Input: unsorted array * Output: sorted array * * * */ public int[] bubbleSort(int[] array) { for (int out = array.length - 1 ; out > 1; out --) { for (int i = 0; i < out; i++) { if (array[i] > array[i+1]) { //swap int temp = array[i]; array[i] = array[i+1]; array[i+1] = temp; } } } return array; }
0 comments:
Post a Comment