直通BAT面试算法精讲课2

本文提供了两种经典的排序算法——冒泡排序和选择排序的实现示例。通过这两个算法的具体代码,展示了如何对整型数组进行升序排列,并对每种方法进行了详细解释。

对于一个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=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
class BubbleSort {
public:
    int* bubbleSort(int* A, int n) {
        int i,j;
        for(i=0;i<n-1;i++){
            for(j=i+1;j<n;j++)
                {
                if(A[i] > A[j])
                    {
                    int temp = A[i];
                    A[i] = A[j];
                    A[j] = temp;
                }
            }
        }
         
          return A;  
   
        // write code here
    }
};
View Code

 选择

class SelectionSort {
public:
    int* selectionSort(int* A, int n) {
        // write code here
        for(int i=0;i<n-1;i++){
            int minIndex=i;
            for(int j=i+1;j<n;j++){
                if(A[j]<A[minIndex]){
                    minIndex=j;
                }
            }
            if(minIndex!=i){
                int temp=A[i];
                A[i]=A[minIndex];
                A[minIndex]=temp;
            }         
        }
        return A;
    }
};
View Code

 

转载于:https://www.cnblogs.com/yuguangyuan/p/6127748.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值