首页 > 解决方案 > 如何修复我的快速排序实现?

问题描述

所以我一直在尝试实现快速排序,但它似乎不起作用它一直给我一个分段错误错误 11 有人可以帮助或提供解决此问题的建议吗?

#include <iostream>
using namespace std;
void _quickSort(int arr[],int lo,int hi);
void quickSort(int arr[]) {
    //lo = low(arr);
    //hi = high(arr);
    _quickSort(arr,0,9);
}
void _quickSort(int arr[], int lo, int hi) {
    int p = lo;
    //cout << lo << "  " << hi << endl;
    for (int i = lo; i < hi;i++) {
        if (arr[i] < arr[p]) {
            cout<<arr[i]<<" <-> "<<arr[p]<<endl;        
            swap(arr[i],arr[p]);
            p = i;
        }

    }
    _quickSort(arr,lo,p);
    _quickSort(arr,p,hi);
}

int main() {
    int a[] = {5,2,7,9,8,3,1,6,4};
    quickSort(a);
    for (int i = 0;i < 9;i++) {
        cout << a[i] << " ";
    }
}

标签: c++

解决方案


    #include <bits/stdc++.h>
    using namespace std;
    
    int _quickSort(int a[], int lb, int ub) {// lb-lower bound     ub-upperbound
        int start=lb;
        int end=ub;
        int pivot=a[lb];
        while(start<end)
        {
            while(a[start]<=pivot)
            start++;
            while(a[end]>pivot)
            end--;
            if(start<end)
            {
                int temp=a[end];
                a[end]=a[start];
                a[start]=temp;
                //cout<<a[start]<<" "<<a[end]<<" "<<pivot<<"\n";
            }
        }
        int temp=a[end];
        a[end]=a[lb];
        a[lb]=temp;
           
        return end;
    }
    
void quickSort(int a[],int lb,int ub) {
    if(lb<ub)
    {
        int pos=_quickSort(a,lb,ub);
        quickSort(a,lb,pos-1);
        quickSort(a,pos+1,ub);
    }
}

int main() {
    
int a[9] = {5,2,7,9,8,3,1,6,4};
    quickSort(a,0,8);
    for (int i = 0;i <=8;i++) 
    {
        cout << a[i] << " ";
    }
}

这是实现快速排序的另一种方式。我刚刚将枢轴的位置返回给另一个函数并从中递归调用 _quicksort。


推荐阅读