未进行/保留对阵列的更改

Changes to array are not being made/kept

本文关键字:阵列 保留      更新时间:2023-10-16

家庭作业的一部分是用C ++以"函数式"编写快速排序。 我已经大部分代码下来了,但我遇到的唯一问题是对数组的更改没有保留。 这是我的代码,我知道它可能看起来不像函数式编程,但我的老师说这很好:

#include <stdio.h>
#include <iostream>
void swap(int* x, int* y);
int partition(int arr[], int low, int high, int cursor);
void quickSort(int A[], int start, int end);
int main(){
    int list[20] = {20, 5, 12, 11, 1, 6, 18, 7, 2, 3, 14, 19, 10, 4, 13, 8, 15, 9, 17, 16};
    quickSort(list,0,19);
    for(int count =0; count<20; count++){
        std::cout<< list[count] << " ";
    }
};
void swap(int* x, int* y){
    int temp = *x;
    *x = *y;
    *y = temp;
};
int partition(int arr[], int low, int high, int cursor){
    if(low == high){
        swap(&arr[cursor+1], &arr[high]);
        return cursor+1;
    }else if(arr[low] <= arr[high]){
        swap(&arr[cursor+1], &arr[low]);
        return partition(arr, low+1, high, cursor+1);
    }else if(arr[low] > arr[high] && low != high){
            return partition(arr, low+1, high, cursor);
    }
};
void quickSort(int A[], int start, int end){
    if(start < end){
        int p = partition(A, start, end, start-1);
        quickSort(A, start, p-1);
        quickSort(A, p+1, end);
    }
};

感谢 timrau 指出缺少的条件,我的问题得到了解决。 一个愚蠢的菜鸟错误,我稍后会踢自己。 谢谢。 如果其他人可能遇到这样的问题,我为解决问题而添加的代码是这样的:

else if(arr[low] > arr[high] && low != high){
    return partition(arr, low+1, high, cursor);
}