cool037

导航

排序算法

冒泡排序(O(n2))

  1. 比较数组中两个相邻的元素,如果第一个数比第二个数大,我们就交换他们的位置
  2. 每一次比较都会产生出一个最大,或者最小的数字
  3. 下一轮则 可以少一次排序
  4. 依次循环,直到结束
package paixu;
import java.util.Arrays;
public class MaoPao {
    public static void main(String[] args){
        int[] a = {1,4,5,6,72,2,2,2,25,6,7};
        int[] result = sort(a);
        System.out.println(Arrays.toString(result));
    }

    public static int[] sort(int[] a){
        int temp = 0;
        for(int i = 0; i<a.length-1; i++){
            for(int j = 0; j<a.length-1-i; j++){
                if (a[j]>a[j+1]){
                    temp = a[j];
                    a[j] = a[j+1];
                    a[j+1] = temp;
                }
            }
        }
        return a;
    }
}

posted on 2025-03-13 11:23  海然  阅读(7)  评论(0)    收藏  举报