gpt4 book ai didi

c++ - 如何修复我的快速排序实现?

转载 作者:行者123 更新时间:2023-12-02 10:14:06 25 4
gpt4 key购买 nike

所以我一直在尝试实现快速排序,但它似乎不起作用
它一直给我一个段错误错误 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] << " ";
}
}

最佳答案

    #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。

关于c++ - 如何修复我的快速排序实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62532511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com