Write a program to Sort an array in descending order using bubble sort


This is a Java program that implements the Bubble Sort algorithm to sort an array of integers in descending order. Here's a step-by-step breakdown of how the program works:

  • Declare and initialize an integer array a with 10 elements.
  • Set i to 0.
  • Enter a while loop that continues until i is less than 10.
  • Inside the loop, set j to 9.
  • Enter a nested while loop that continues until j is greater than i.
  • Inside the nested loop, compare a[j] with a[j-1] . If a[j] is greater than a[j-1], swap the two values.
  • Decrement j by 1.
  • After the nested loop completes, increment i by 1.
  • Repeat steps 4-8 until the outer loop completes.
  • After the sorting is complete, print the sorted array in descending order using a while loop and the println() method.

Source Code

public class Bubble_Sort
{
	public static void main(String[] args) 
	{
		int i = 0;
		int j = 0;
		int t = 0;
		int a[] = {2, 65, 23, 13, 18, 30, 46, 17, 52, 78};
 
		while(i < 10)
		{
			j = 9;
			while(j > i)
			{
				if(a[j] > a[j - 1])
				{
					t = a[j];
					a[j] = a[j - 1];
					a[j - 1] = t;
				}
				j = j - 1;
			}
			i = i + 1;
		}
 
		System.out.println("Sorted Array in Descending Order .. ");
		i = 0;
		while(i < 10)
		{
			System.out.print(a[i] + " ");
			i = i + 1;
		}
	}
}

Output

Sorted Array in Descending Order ..
78 65 52 46 30 23 18 17 13 2

Example Programs