查找数组中的最大和最小元素

Find the maximum and minimum element in an array

在这个问题中我找不到错误对我来说一切似乎都是正确的,我正在使用快速排序对数组进行排序但是排序算法不起作用,所以我可以找到最大值和分钟

#include <iostream>
#include <vector>

using namespace std;

void swap(int *a, int *b){
    int t = *a;
    *a = *b;
    *b = t;
}

int partition(vector<int> arr ,int low, int high){
    int pivot = arr[high];
    int i = low-1;
    for (int j=low; j<=high; j++){
        if(arr[j]<pivot){
            i++;
            swap(&arr[i],&arr[j]);
        }
    }
    swap(&arr[i+1],&arr[high]);
    return (i+1);
}

void quickSort(vector<int> arr, int low, int high){
    if(low<high){
        int pi = partition(arr,low,high);
        quickSort(arr,low,pi-1);
        quickSort(arr,pi+1,high);
    }
}


int main()
{
    vector<int> arr = {5,2,3,4,1};
    int arr_size = arr.size();
    quickSort(arr,0,arr_size-1);
    cout<<"The minimum and maximum array is \n";
    cout<<arr[0]<<" "<<arr[arr_size-1];

    return 0;
}

quicksort()partition()中:

int partition(vector<int> arr ,int low, int high){
    int pivot = arr[high];
    int i = low-1;
    for (int j=low; j<=high; j++){
        if(arr[j]<pivot){
            i++;
            swap(&arr[i],&arr[j]);
        }
    }
    swap(&arr[i+1],&arr[high]);
    return (i+1);
}
void quickSort(vector<int> arr, int low, int high){
    if(low<high){
        int pi = partition(arr,low,high);
        quickSort(arr,low,pi-1);
        quickSort(arr,pi+1,high);
    }
}

您按值传递 vector<int> arr,这意味着编译器将复制 arr,而不更改 arr 的实际值。

您必须改为通过引用传递:

int partition(vector<int> &arr ,int low, int high){
    int pivot = arr[high];
    int i = low-1;
    for (int j=low; j<=high; j++){
        if(arr[j]<pivot){
            i++;
            swap(&arr[i],&arr[j]);
        }
    }
    swap(&arr[i+1],&arr[high]);
    return (i+1);
}
void quickSort(vector<int> &arr, int low, int high){
    if(low<high){
        int pi = partition(arr,low,high);
        quickSort(arr,low,pi-1);
        quickSort(arr,pi+1,high);
    }
}

但是,您也可以改用 std::sort。在 main():

int main()
{
    std::vector<int> arr = {5,2,3,4,1};
    int arr_size = (int)arr.size();
    std::sort(arr.begin(), arr.end());
    std::cout<<"The minimum and maximum array is \n";
    std::cout<<arr[0]<<" "<<arr[arr_size-1];

    return 0;
}

但一般来说,“排序”解决方案效率低下。您应该改用 std::minmax_element

int main()
{
    std::vector<int> arr = {5,2,3,4,1};
    auto result = std::minmax_element(arr.begin(), arr.end());
    std::cout<<"The minimum and maximum array is \n";
    std::cout<< *result.first <<' '<< *result.second;

    return 0;
}