对于一个int数组,请编写一个冒泡排序算法,对数组元素排序。

给定一个int数组A及数组的大小n,请返回排序后的数组。 

测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
冒泡: 依次比较相邻,大的放后面。
class BubbleSort {
public:
    int* bubbleSort(int* A, int n) {
        // write code here
        for(int i=0;i<n;i++){
            for(int j=i+1;j<n;j++){
                if(A[i]>A[j]){
                    swap(A[i],A[j]);
                    
                }
            } 
        }
        return A;
    }
};

 

直通BAT面试算法精讲课2
class BubbleSort {
public:
    int* bubbleSort(int* A, int n) {
        // write code here
        for(int i=0;i<n;i++){
            for(int j=n-1;j>i;j--){
                if(A[j]<A[j-1]){
                    int tmp = A[j];
                    A[j]=A[j-1];
                    A[j-1]=tmp;
                }
            }
        }
        return A;
    }
};
View Code

相关文章:

  • 2022-12-23
  • 2021-04-23
  • 2021-04-18
  • 2021-11-03
  • 2021-09-09
  • 2021-04-19
  • 2021-07-16
  • 2022-01-10
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-14
  • 2021-04-24
  • 2021-10-07
  • 2021-09-08
相关资源
相似解决方案