Bubble Sort

It’s really been a very long time since I had wrote something, So many things were going which were kind of keeping me very busy, But I finally managed to get some time.. yay!!! yepeee!!, So to continue my journey towards CS algorithms,  I had tried the Bubble Sort with single loop.

Steps are like:
For any given Array:
Take the first two elements and move the largest to the right, and keep doing that unless the largest reached at the position where either its the last position of array or the the position where its right is already the largest and then again repeat and do until all the largest values moves to the right side of array.

Here is the example: Your inputs are highly appreciated 🙂

import java.util.Arrays;

import java.util.Random;

public class BubbleSortV1 {

public static void main(String[] args) {

int[] arr = fillArray();

System.out.println(“Unsorted Array :: “ + Arrays.toString(arr));


System.out.println(“Sorted Array :: “ + Arrays.toString(arr));



private static void verifyArray(int[] arr) {

booleans = true;

for (int i = 0; i < 99; i++) {

if (arr[i] > arr[i + 1]) {

System.out.println(“not sorted…”);

s = false;




if (s) {

System.out.println(“all sorted;”);



static int[] fillArray() {

int[] arr = new int[100];

Random r = new Random();

for (int i = 0; i < 100; i++) {

arr[i] = r.nextInt(500);




// read from left to right and

// move the largest item to the right

// that way all large would be on right side and small on left side

static void bubbleSort(int[] arr) {

// store the last unsorted index

int sortedPartIndex = arr.length;

// first bucket

int leftBucketIndex = 0;

// second bucket

int rightBucketIndex = 1;

// keep running until sorted index reaches 0 (right to left)

while (sortedPartIndex > 0) {

if (arr[leftBucketIndex] > arr[rightBucketIndex]) {

int tempBucket = arr[rightBucketIndex];

arr[rightBucketIndex] = arr[leftBucketIndex];

arr[leftBucketIndex] = tempBucket;




if (rightBucketIndex >= sortedPartIndex) {

// decrement the sorted part index

sortedPartIndex = sortedPartIndex – 1;

// reste the left and right bucket index to default, to start

// over

leftBucketIndex = 0;

rightBucketIndex = 1;






Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s