/**
* @author 薛莲婷
*冒泡排序Bubble Sort
*自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。
*即:每当两相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换
*
*简单选择排序Simple Selection Sort
*每次在剩余的(n-i)个未排好序的数中找到最小的那个,与当前下标为i的数进行交换
*直至所有数都已有序排列
*/
import java.util.*;
class Sort {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
Sort sort=new Sort();
int []a={49,38,65,97,76,27,49,13};
System.out.println("请选择:1、冒泡排序,2、选择排序");
int x=sc.nextInt();
switch(x){
case 1:a=sort.bubbleSort(a);break;
case 2:a=sort.simpleSelectionSort(a);break;
default:System.out.print("输入有误");
}
sc.close();
}
void display(int a[]){
for(int i=0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
int[] bubbleSort(int a[]){
Sort sort=new Sort();
int temp;
for(int i=0;i<a.length-1;i++){ //i<a.length-1
for(int j=0;j<a.length-i-1;j++){ //j<a.length-i-1
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
sort.display(a);
System.out.print("\n");
}
return a;
}
/*38 49 65 76 27 49 13 97
38 49 65 27 49 13 76 97
38 49 27 49 13 65 76 97
38 27 49 13 49 65 76 97
27 38 13 49 49 65 76 97
27 13 38 49 49 65 76 97
13 27 38 49 49 65 76 97 */
int[] simpleSelectionSort(int a[]){
Sort sort=new Sort();
int temp;
int minIndex;
for(int i=0;i<a.length-1;i++){
minIndex=i;
for(int j=i+1;j<a.length;j++){
if(a[minIndex]>a[j]){
minIndex=j;
}
}
if(a[minIndex]!=a[i]){
temp=a[i];
a[i]=a[minIndex];
a[minIndex]=temp;
}
sort.display(a);
System.out.print("\n");
}
return a;
}
/*13 38 65 97 76 27 49 49
13 27 65 97 76 38 49 49
13 27 38 97 76 65 49 49
13 27 38 49 76 65 97 49
13 27 38 49 49 65 97 76
13 27 38 49 49 65 97 76
13 27 38 49 49 65 76 97*/
}
冒泡排序,简单选择排序
最新推荐文章于 2022-04-29 23:24:15 发布