c++ - 如何修复我的快速排序实现?
问题描述
所以我一直在尝试实现快速排序,但它似乎不起作用它一直给我一个分段错误错误 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。
推荐阅读
- google-chrome-extension - 如何将 Chrome 扩展程序图标添加到 Chrome 网上应用店(新仪表板)
- python - 如何重新分配欧洲街道地址以删除字母/数字
- angular - Angular:防止 api 错误不显示 HTML 模板
- javascript - 阻止表单提交
- android - 限制android进程的日志级别
- java - 在 Java Spring boot 中有没有一种方法可以将单个 kafka 队列用于不同的 Java 对象?
- python - 如何抓取受密码保护的网站
- java - 将没有 web 项目的 springboot 打包到一个可运行的 Jar 并由 java -jar 运行,但 @Scheduled 方法不起作用
- amazon-web-services - 如何将 aws sumerian acene 与 aws iot 核心连接起来?
- azure - 通过 Powershell 脚本将 swagger 导入 APImanagement 在 Azure devops 管道中不起作用