快速排序,要求用 fun(int*a,int n),n是数组长度,不知道哪儿错了
void fun(int* a, int n)
{
int i = 0, j = n;
int x = a[i];
while (i < j)
{
while (i < j && a[j] >= x) { j--; }
if (i < j) { a[i] = a[j]; }
while (i < j && a[i] <= x) { i++; }
if (i < j) { a[j] = a[i]; }
}
a[i] = x;
fun(a-i-1, i);
fun(a-i+1, n-i);
}
int main()
{
int a[100];
int n;
cout << "请输入要排序的个数:";
cin >> n;
cout << "请输入" << n << "个数:";
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
fun(a, n);
cout << "排序为:";
for (int j = 0; j < n; j++)
{
cout << a[j] << " ";
}
cout << endl;
return 0;
}
选择排序参考代码如下:
void fun(int* a, int n) {
if (n < 2) {
return;
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (a[i] > a[j]) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
if (i < j) { a[i] = a[j]; }
这是干啥呢?这么赋值不就覆盖掉了?至少得交换吧
这个不是快排吧,给你个参考:
#include<iostream>
using namespace std;
//交换函数swap
void swap1(int& a, int& b)
{
int temp = a; a = b; b = temp;
}
//做一个把数组分两半的函数
int sortSecond(int A[], int low, int high)
{
int P = A[high];//基数选择右边界
while (low < high)
{
while (low < high && A[low] <= P)
low++;//左边部分小的跳过
if (low < high){
swap1(A[low], A[high--]);//大的扔到后面并使右边界减一
}
while (low<high && A[high]>=P)
high--;//右边大的跳过
if (low < high) {
swap1(A[low++], A[high]);//小的扔到前面并使左边界加一
}
}
return low;//此时low=high
}
void fastSort(int A[], int low, int high)
{
if (low > high) return;//递归结束条件 low>high
int v = sortSecond(A, low, high);
fastSort(A, low, v - 1);//对左区间递归排序
fastSort(A, v + 1, high);//对右区间递归排序
}
int main()
{
int A[9] = {4,3,1,2,4,9,5,8,6};
int len = sizeof(A) / sizeof(A[0]);
cout << "排序前数组为:\t" << endl;
for (int i = 0; i < len; i++)
{
cout << A[i] << " ";
}
cout << endl;
fastSort(A, 0, len-1);//时间复杂度 平均情况O(nlogn),最坏情况O(n^2)
cout << "快速排序后数组为:\t" << endl;
for (int i = 0; i < len; i++)
{
cout << A[i] << " ";
}
}
我以为写完就完事了,没想到老师又说这不是快排,我滴个天,还要咋样才叫快排