冒泡排序,简单选择排序


/**
 * @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*/

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值