Category Archives: Algorithms

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));

bubbleSort(arr);

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

verifyArray(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;

break;

}

}

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);

}

returnarr;

}

// 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;

}

leftBucketIndex++;

rightBucketIndex++;

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;

}

}

}

}