博前感想:
这是自己写的代码,用递归实现的,其实还可用非递归的实现。
排数组:
#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
int povotkey;
void create(int *(&a), int &(n)) //&a相当于全局变量,但是要在main函数里面定义。把a的地址作为变量了。
{
cin >> n;
a = new int[n + 1];
for (int i = 1; i < n + 1; i++)
{
cin >> a[i];
}
//a[0] = a[1];
}
int partition_hwq(int *a, int low, int high)
{
povotkey = a[low]; //把分割值通过low来赋值
a[0] = povotkey; //把分割值复制到数组零号位置
while (high > low)
{
while (low < high&&a[high] >= povotkey)
{
--high;
}
a[low] = a[high];
while (low < high&&a[low] <= povotkey)
{
++low;
}
a[high] = a[low];
}
a[low] = a[0]; //这个条件很关键。把旧的分割值记录到新的分割位置。分割值一直是一个数
return low; //这时候low和high在同一个位置
}
void qsort(int *a, int low, int high)
{
if (low < high)
{
partition_hwq(a, low, high);
qsort(a, low, partition_hwq(a, low, high) - 1);
qsort(a, partition_hwq(a, low, high) + 1, high);
}
}
void quicksort(int *a, int n)
{
qsort(a, 1, n);
}
int main()
{
int *hwq;
int n;
create(hwq, n);
quicksort(hwq, n);
for (int j = 1; j < n + 1; j++)
{
cout << hwq[j] << " ";
}
//quicksort(hwq);
system("pause");
return 0;
}
排结构体:
#include<iostream>
#include<cmath>
using namespace std;
typedef struct node
{
node *next;
int data;
}Node,*no;
int povotkey; //分割指
void create(no &h,int &(n))
{
cout<<"请输入要创建的结构体个数:"<<endl;
cin>>n;
h=new Node[n+1];
for(int i=1;i<n+1;i++)
{
cout<<"请输入第"<<i+1<<"个结构体的数据:"<<endl;
cin>>h[i].data;
}
//h=&h[0];
}
int partition(no h,int low,int high)
{
povotkey=h[low].data;
h[0].data=povotkey;
while(high>low)
{
while(low<high&&h[high].data>=povotkey)
{
--high;
}
h[low].data=h[high].data;
while(low<high&&h[low].data<=povotkey)
{
++low;
}
h[high].data=h[low].data;
}
h[low].data=h[0].data;
return low;
}
void qsort(no h,int low,int high)
{
if(low<high)
{
partition(h,low,high);
qsort(h,low,partition(h,low,high)-1);
qsort(h,partition(h,low,high)+1,high);
}
}
void quicksort(no h,int n)
{
qsort(h,1,n);
}
int main()
{
no hwq;
int n;
create(hwq,n);
quicksort(hwq,n);
for(int i=1;i<n+1;i++)
{
cout<<hwq[i].data<<" ";
}
return 0;
}
用递归实现的,其中数组的第0个位置用来保存分隔值。希望大家给我提建议和意见啊。