题目

给一组整数,按照升序排序,使用选择排序,冒泡排序,插入排序或者任何 O(n2) 的排序算法。

解题

冒泡排序

public class Solution {
    /**
     * @param A an integer array
     * @return void
     */
    public void sortIntegers(int[] A) {
        // Write your code here
        if(A==null || A.length<=1)
            return;
        int n = A.length;
        for(int i=n-1;i>=0;i--){
            
            for(int j=0;j<i;j++){
                if(A[j]>A[j+1]){
                    swap(A,j,j+1);
                }
            }
        }
    }
    public void swap(int[] A,int i,int j){
        int tmp = A[i];
        A[i] = A[j];
        A[j] = tmp;
    }
}

 

相关文章:

  • 2021-11-24
  • 2022-12-23
  • 2021-09-25
  • 2021-12-29
  • 2022-12-23
  • 2021-12-10
  • 2021-12-20
  • 2021-09-20
猜你喜欢
  • 2021-05-19
  • 2022-12-23
  • 2021-12-02
  • 2021-06-05
  • 2021-09-17
  • 2021-11-15
相关资源
相似解决方案