java写的一个冒泡排序

一、冒泡排序:

冒泡排序是一种简单的排序算法,它重复地遍历待排序的数列,比较每对相邻的元素,如果它们的顺序错误就把它们交换过来。遍历数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。


public class Simple1 {
 
 public static void main(String[] args) {
   int []a ={21,42,32,54,31,12,23};
   int len=a.length;
   System.out.println("待排的数组:");
   for (int i = 0; i < len; i++) {
    System.out.print(a[i]+" ");
  
 }
  //冒泡排序
   
   int temp;
   for (int j = 0; j<len; j++) {
    for (int i = len-1; i>j; i--) {
     if(a[i]<a[i-1]){
      temp=a[i-1];
         a[i-1]=a[i];
      a[i]=temp;
     }
   
  }
 }
  
  System.out.println();
     System.out.println("排好的数组:");
     for (int i = 0; i < len; i++) {
      System.out.print(a[i]+" ");
  
 }
 }

}

二、冒泡排序的实际应用

public class BubbleSort {  
    void bubbleSort(int arr[]) {  
        int n = arr.length;  
        for (int i = 0; i < n-1; i++)  
            for (int j = 0; j < n-i-1; j++)  
                if (arr[j] > arr[j+1]) {  
                    // swap arr[j+1] and arr[j]  
                    int temp = arr[j];  
                    arr[j] = arr[j+1];  
                    arr[j+1] = temp;  
                }  
    }  
  
    /* Prints the array */  
    void printArray(int arr[]) {  
        int n = arr.length;  
        for (int i=0; i<n; ++i)  
            System.out.print(arr[i]+" ");  
        System.out.println();  
    }  
  
    // Test the code  
    public static void main(String args[]) {  
        BubbleSort bs = new BubbleSort();  
        int arr[] = {64, 34, 25, 12, 22, 11, 90};  
        bs.bubbleSort(arr);  
        System.out.println("Sorted array");  
        bs.printArray(arr);  
    }  
}

这个程序首先定义了一个冒泡排序的方法bubbleSort,这个方法遍历数组并对每对相邻的元素进行比较。如果它们的顺序是错误的(即,第一个元素大于第二个元素),那么就交换这两个元素。这个过程会重复进行,直到整个数组都按照正确的顺序排列。最后,main方法创建一个BubbleSort对象,并使用这个对象对一个数组进行排序,然后打印出排序后的数组。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

奋力向前123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值