Bubble Sort in Java

Ads
 

Bubble Sort in Java

Bubble Sort aka exchange sort in Java is used to sort integer values. This algorithm compares and swaps each pair of adjacent elements till the list is sorted. Swapping is followed carried out repeatedly till the list is sorted. Bubble Sort compares first pair of adjacent elements and put larger value at higher index. Bubble Sort is a slow and lengthy way to sort elements.

Bubble Sort aka exchange sort in Java is used to sort integer values. This algorithm compares and swaps each pair of adjacent elements till the list is sorted. Swapping is followed carried out repeatedly till the list is sorted. Bubble Sort compares first pair of adjacent elements and put larger value at higher index. Bubble Sort is a slow and lengthy way to sort elements.

Bubble Sort aka exchange sort in Java is used to sort integer values. This algorithm compares and swaps each pair of adjacent elements till the list is sorted. Swapping is followed carried out repeatedly till the list is sorted.

Bubble Sort compares first pair of adjacent elements and put larger value at higher index. Then it compares next pair of elements and repeats the same process. When it reaches the last two pair and puts the larger value at higher index, it goes back to first pair. The process of comparing, swapping and returning to first pair of element is carried out till the whole list is sorted and no swaps are needed.

Bubble Sort is a slow and lengthy way to sort elements.

Example of Bubble Sort in Java:

public class BubbleSort {
	public static void main(String a[]) {
		int i;
		int array[] = { 12, 9, 4, 99, 120, 1, 3, 10 };
		System.out.println("Value befor the sort:");
		for (i = 0; i < array.length; i++)
		System.out.print(array[i] + "  ");
		System.out.println();
		bubble_srt(array, array.length);
		System.out.print("Values after the sort:\n");
		for (i = 0; i < array.length; i++)
		System.out.print(array[i] + "  ");
		System.out.println();
	}

	public static void bubble_srt(int x[], int n) {
		int i, j, t = 0;
		for (i = 0; i < n; i++) {
			for (j = 1; j < (n - i); j++) {
				if (x[j - 1] > x[j]) {
					t = x[j - 1];
					x[j - 1] = x[j];
					x[j] = t;
				}
			     }
		          }
	                }
                      }

Output:

Unsorted Value:

12 9 4 99 120 1 3 10

Sorted Value:

1 3 4 9 10 12 99 120

Ads

Ads