Write a Java program to perform the bubble sort on integer array items using for loop. In this Java example, we use multiple for loops to iterate the integer array, compare the adjacent numbers, and swap them.
package RemainingSimplePrograms;
import java.util.Scanner;
public class BubbleSortNumber1 {
private static Scanner sc;
public static void main(String[] args) {
int i, j, Size, temp;
sc = new Scanner(System.in);
System.out.print("Enter the Array size = ");
Size = sc.nextInt();
int[] arr = new int[Size];
System.out.format("Enter Array %d elements = ", Size);
for(i = 0; i < Size; i++)
{
arr[i] = sc.nextInt();
}
System.out.println("Sorting Integers using the Bubble Sort");
for(i = 0; i < Size; i++)
{
for(j = 0; j < Size - i - 1; j++)
{
if(arr[j + 1] > (arr[j]))
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
System.out.println(arr[j]);
}
}
}
It is another example to Perform Bubble Sort on integers.
package RemainingSimplePrograms; import java.util.Scanner; public class BubSrtNum2 { private static Scanner sc; public static void main(String[] args) { int i, j, Size, temp; sc = new Scanner(System.in); System.out.print("Enter the Array size = "); Size = sc.nextInt(); int[] arr = new int[Size]; System.out.format("Enter Array %d elements = ", Size); for(i = 0; i < Size; i++) { arr[i] = sc.nextInt(); } System.out.println("Sorting Integers using the Bubble Sort"); for(j = 0; j < Size; j++) { for(i = j + 1; i < Size; i++) { if(arr[i] < (arr[j])) { temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } System.out.println(arr[j]); } } }
Enter the Array size = 5
Enter Array 5 elements = 14 99 5 25 11
Sorting Integers using the Bubble Sort
5
11
14
25
99
The Bubble Sort Program on Integers using a while loop.
package RemainingSimplePrograms; import java.util.Scanner; public class BubSrtNum3 { private static Scanner sc; public static void main(String[] args) { int i, j, Size, temp; sc = new Scanner(System.in); System.out.print("Enter the Array size = "); Size = sc.nextInt(); int[] arr = new int[Size]; System.out.format("Enter Array %d elements = ", Size); for(i = 0; i < Size; i++) { arr[i] = sc.nextInt(); } System.out.println("Sorting Integers using the Bubble Sort"); i = 0; while( i < Size) { j = 0; while( j < Size - i - 1) { if(arr[j + 1] > (arr[j])) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } j++; } System.out.println(arr[j]); i++; } } }
Enter the Array size = 7
Enter Array 7 elements = 11 88 7 64 1 99 55
Sorting Integers using the Bubble Sort
1
7
11
55
64
88
99