gpt4 book ai didi

c++ - 如何使快速排序递归?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:44:35 25 4
gpt4 key购买 nike

目前我正在尝试进行递归快速排序。快速排序有很多不同的方法,但对于我的方法,我必须取数组的第一个元素,并且始终使用数组的第一个元素作为基准。然后我将它与所有元素进行比较并获得比较总数。小于数组的元素应该在枢轴后面,然后是更大的元素。所以它应该是枢轴|元素小于枢轴|元素大于枢轴。比较完所有的枢轴后,你应该把边上最后一个比枢轴小的元素和前面的枢轴交换。目前我不知道如何使它递归,因为我相信我已经成功地编写了第一遍代码。我一直在尝试使其递归,以便它会调用自身的多次传递并且它们被拆分。重新对所有内容进行排序将是愚蠢的。相反,它应该将数组分成两部分,并递归小于原始枢轴的一侧和大于原始枢轴的一侧。这是一个测试用例,因为我后来不得不在 10,000 个数字的数据文件上使用这个算法(这就是为什么我使用 long long 虽然现在我想起来,它可能是矫枉过正)。

下面是我的 C++ 代码:

    #include <stdio.h>
#include <iostream>
using namespace std;

long long quicksort(long long arr[],long long leftbegin, long long rightend)
{
long long i = leftbegin + 1;
long long pivot = arr[leftbegin];
long long comparisons = 0;
for(long long j = i; j < 8; j++)
{
if(arr[j] > pivot)
{
rightend++;
comparisons ++;
}
if(arr[j] < pivot)
{
long long temp = 0;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
comparisons ++;
i = i+1;
}
}
long long temp = 0;
temp = arr[0];
arr[0] = arr[i-1];
arr[i-1] = temp;
// for(int x = 0; x< 8; x++)
// {
// if(arr[x+1] >= arr[x])
// {
//
// }
// else
// {
// quicksort(arr,0,i);
// quicksort(arr,i+1,(rightend + 0));
// }
// }
//
return comparisons;
}

/* Driver program to test above functions */
int main ()
{
long long arr[8]= {3,8,2,5,1,4,7,6};
cout<<"the number of comparisons are "<<quicksort(arr,0,8)<<endl;
cout<<endl<<"arr is "<<endl;
for(int i = 0; i < 8; i++)
{
cout<<arr[i]<<endl;
}

}

如果我删除注释并运行带有注释部分的代码,它会在 long long temp = 0; 处给我错误,它会说 exec bad access,即使它能够成功运行。如果重要的话,我会使用 mac 和 Xcode。

最佳答案

这是使用递归的 QuickSort 的 C++ 实现:

#include <cstdio>
#include <algorithm>

using namespace std;
int partition (int arr[], int low, int high)
{
int pivot = arr[high]; //taking the last element as pivot
int i = (low - 1);
for (int j = low; j <= high- 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return (i + 1);
}

void quickSort(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()
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr)/sizeof(arr[0]);
quickSort(arr, 0, n-1);

return 0;
}

关于c++ - 如何使快速排序递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31720408/

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