Dutch flag series of questions

Problem: Given a number and an array arr num, num Please count is smaller than on the left of the array, is equal to the number in the middle num array, num greater than the number on the right side of the array.
It requires additional space complexity O (1), the time complexity of O (N)

#include <iostream>
using namespace std;


void Swap(int arr[], int i, int j){
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

int partition(int arr[], int L, int R, int num){
    int les = L - 1;
    int more = R + 1;
    int cur = L;
    while (cur < more){
        if (arr[cur] < num){
            Swap(arr, ++les, cur++);
        }
        else if (arr[cur] > num){
            Swap(arr, --more, cur);
        }
        else{
            cur++;
        }
    }
     cout << '[' << les + 1 << ',' << more - 1 << ']' << endl;
}

int main(){
    int arr[100] = {5,3,6,5,3,5,8,9};
    int num = 5;
    int L = 0, R = 7;
    partition(arr, L, R, num);
}

Released four original articles · won praise 0 · Views 89

Guess you like

Origin blog.csdn.net/weixin_44177074/article/details/104344832