JAVA排序,冒泡
键盘输入一组数据,使用冒泡法进行排序(降序+升序)
/**@文件名: BubbleSort.java
* @类功能说明: 冒泡排序
* @作者: LiYuHui
* @Email: 1327711913@qq.com
* @日期: 2020年5月11日下午4:49:16
* @修改说明:<br>
* <pre>
* <li>作者: LiYuHui</li>
* <li>日期: 2020年5月11日下午4:49:16</li>
* <li>内容: </li>
* </pre>
*/
public class BubbleSort {
/*
* 需求:
* 冒泡降序
* 分析:
* 1、给定数组,遍历数组
* 2、如果前一个比后一个大,换位置,否则,位置不变,进行排序
*/
/**
* @方法名: descSort
* @方法说明: 冒泡降序
* @作者: LiYuHui
* @邮箱:1327711913@qq.com
* @日期: 2020年5月11日下午5:03:37
* @param array
* @return: void
*/
public void descSort(int[] array){
for(int i=0;i<array.length;i++){
for(int j=0;j<array.length-i-1;j++){
if(array[j]<array[j+1]){
int temp=0;
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
System.out.println("经过冒泡降序后的结果为:");
for (int n : array) {
System.out.print(n+" ");
}
}
/**
* @方法名: ascSort
* @方法说明:冒泡升序
* @作者: LiYuHui
* @邮箱:1327711913@qq.com
* @日期: 2020年5月11日下午5:24:54
* @param array
* @return: void
*/
public void ascSort(int[] array){
for(int i=0;i<array.length;i++){
for(int j=0;j<array.length-i-1;j++){
if(array[j]>array[j+1]){
int temp=0;
temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
}
System.out.println("经过冒泡升序后的结果为:");
for (int n : array) {
System.out.print(n+" ");
}
}
}
/**@文件名: TestBubbleSort.java
* @类功能说明: 测试冒泡排序
* @作者: LiYuHui
* @Email: 1327711913@qq.com
* @日期: 2020年5月11日下午5:03:03
* @修改说明:<br>
* <pre>
* <li>作者: LiYuHui</li>
* <li>日期: 2020年5月11日下午5:03:03</li>
* <li>内容: </li>
* </pre>
*/
public class TestBubbleSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入数组的长度:");
int length = sc.nextInt();
//根据键盘输入的长度,确定数组的长度
int[] array=new int[length];
System.out.println("请输入数组的内容:");
for(int i=0;i<array.length;i++){
array[i]=sc.nextInt();
}
BubbleSort bubbleSort = new BubbleSort();
bubbleSort.descSort(array);
bubbleSort.ascSort(array);
}
}