刷题笔记18——数组中小于等于num的元素放左边

题目描述

给定一个值num和一个数组,把小于等于num的数放在数组左边,大于num的数放在数组右边

解法1:单指针规定小于等于范围

刷题笔记18——数组中小于等于num的元素放左边_第1张图片

解法2:双指针相对而行

刷题笔记18——数组中小于等于num的元素放左边_第2张图片

测试结果及代码

刷题笔记18——数组中小于等于num的元素放左边_第3张图片

#include 
#include 
using namespace std;

const int num = 5;

void printArray(int a[], int N) {
    for (int i = 0; i < N; ++i) {
        cout << a[i] << " ";
    }
    cout << endl;
}

void Swap(int &x, int &y) {
    int t = x;
    x = y;
    y = t;
}

void compare(int a[], int N) {
    int i = 0;
    int j = N - 1;
    while (i < j) {
        while (a[i] <= num)
            i++;
        while (a[j] > num)
            j--;
        if (i < j)
            Swap(a[i], a[j]);
        else
            break;
    }
}

void test(int a[], int N) {
    int left = 0;
    int i;
    for (i = 0; i < N; ++i) {
        if (a[i] <= num) {
            Swap(a[left], a[i]);
            left++;
        }
    }
}

int main (int argc, char* argv[]) {

    srand(time(NULL));
    const int size = 15;           // 随机生成的数组大小
    const int test_time = 10;      // 测试次数
    int a[size] = {0};             // 原始数组
    int tmp1[size] = {0};          // 测试数组
    int tmp2[size] = {0};          // 对比数组
    int tmp3[size] = {0};          // 展示数组

    for (int cnt = 0; cnt < test_time; ++cnt) {
        for (int i = 0; i < size; ++i) {
            a[i] = rand() % 10 + 1;
        }
        for (int i = 0; i < size; ++i) {
            tmp1[i] = a[i];
            tmp2[i] = a[i];
            tmp3[i] = a[i];
        }
        cout << "第 " << cnt << " 次生成:";
        printArray(tmp3, size);
        compare(tmp1, size);
        cout << "第 " << cnt << " 次对比:";
        printArray(tmp1, size);
        test(tmp2, size);
        cout << "第 " << cnt << " 次测试:";
        printArray(tmp2, size);
        cout << endl;
    }

    return 0;
}

你可能感兴趣的:(刷题)