关于整数的Java气泡排序程序

324 阅读1分钟

编写一个Java程序,使用for循环对整数数组项目进行冒泡排序。在这个Java例子中,我们使用多个for循环来迭代整数数组,比较相邻的数字,并将它们交换。

// 使用嵌套for循环对整数进行泡沫排序的Java程序 包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\]);
	}
}

image.png

这是另一个对整数进行泡沫排序的Java例子

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

使用while循环对整数进行Java泡沫排序程序。

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