0交换排序

长度为n的数组乱序存放着0至n-1. 现在只能进行0与其他数的交换,完成以下函数

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <array>
using namespace std;


/**
* 交换数组里n和0的位置
* array: 存储[0-n)的数组
* len: 数组长度
* n: 数组里要和0交换的数
*/
extern void swap_with_zero(int* array, int len, int n);

class Solution {
public:
    /**
    * 调用方法swap_with_zero来对array进行排序
    */
    void sort(int* array, int len)
    {
    }
};

答案如下:

#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
#include <unordered_set>
#include <queue>
#include <stack>
#include <string>
#include <climits>
#include <algorithm>
#include <sstream>
#include <functional>
#include <bitset>
#include <numeric>
#include <cmath>
#include <regex>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <array>
using namespace std;


/**
* 交换数组里n和0的位置
* array: 存储[0-n)的数组
* len: 数组长度
* n: 数组里要和0交换的数
*/
extern void swap_with_zero(int* array, int len, int n);

class Solution {
public:
    /**
    * 调用方法swap_with_zero来对array进行排序
    */
    void sort(int* array, int len)
    {
        if (len <= 1)
            return;
        else
        {
            for (int i = 0; i < len; i++)
            {
                if (array[i] != i)
                {
                    swap_with_zero(array, len, i);
                    while (array[0] != 0)
                        swap_with_zero(array, len, array[0]);
                }
            }

        }
    }
};

猜你喜欢

转载自blog.csdn.net/jackzhang_123/article/details/80869851