关于排序(for 复习)
如果有大佬进来看了,请指点指点
归并排序
菜鸟上看的,不是太理解
template<typename T> // 整數或浮點數皆可使用,若要使用物件(class)時必須設定"小於"(<)的運算子功能
void merge_sort(T arr[], int len) {
T *a = arr;
T *b = new T[len];
for (int seg = 1; seg < len; seg += seg) {
for (int start = 0; start < len; start += seg + seg) {
int low = start, mid = min(start + seg, len), high = min(start + seg + seg, len);
int k = low;
int start1 = low, end1 = mid;
int start2 = mid, end2 = high;
while (start1 < end1 && start2 < end2)
b[k++] = a[start1] < a[start2] ? a[start1++] : a[start2++];
while (start1 < end1)
b[k++] = a[start1++];
while (start2 < end2)
b[k++] = a[start2++];
}
T *temp = a;
a = b;
b = temp;
}
if (a != arr) {
for (int i = 0; i < len; i++)
b[i] = a[i];
b = a;
}
delete[] b;
}
归并 用全局变量
const int maxn=2005;
int a[maxn];
int tmp[maxn];
int t,n;
int ans;
void Merge(int l,int m,int r)
{
int i=l;
int j=m+1;
int k=l;
while(i<=m&&j<=r)
{
if(a[i]>a[j])
{
tmp[k++]=a[j++];
ans+=m-i+1;
}
else
{
tmp[k++]=a[i++];
}
}
while(i<=m)tmp[k++]=a[i++];
while(j<=r)tmp[k++]=a[j++];
for(int i=l;i<=r;i++)
a[i]=tmp[i];
}
void Merge_sort(int l,int r)
{
if(l<r)
{
int m=(l+r)>>1;
Merge_sort(l,m);
Merge_sort(m+1,r);
Merge(l,m,r);
}
}
归并 非全局变量
void merger(int a[],int low,int mid,int high)
{
int i,j,k;
i=low,j=mid+1,k=low;
while(i<=mid&&j<=high)
if(a[i]>a[j])
{
temp[k++]=a[j++];
ans+=mid+1-i;
}
else
temp[k++]=a[i++];
while(i<=mid)
temp[k++]=a[i++];
while(j<=high)
temp[k++]=a[j++];
for(i=low;i<=high;i++)
a[i]=temp[i];
}
void merge_sort(int a[],int low,int high)
{
if(low<high)
{
int mid=(low+high)/2;
merge_sort(a,low,mid);
merge_sort(a,mid+1,high);
merger(a,low,mid,high);
}
}
快速排序 全局变量
const int N =100005;
int num[N];
int partition1(int low,int high)
{
int i=low,j=high,pivot=num[low];
while(i<j)
{
while(i<j&&num[j]>=pivot)
--j;
int t=num[i];
num[i]=num[j];
num[j]=t;
while(i<j&&num[i]<=pivot)
++i;
swap(num[i],num[j]);
}
return i;
}
void quick_sort(int low,int high)
{
if(low<high)
{
int x=partition1(low,high);
quick_sort(low,x-1);
quick_sort(x+1,high);
}
}
快排 非全局
void quick_sort(int a[],int s,int t)
{
int i=s,j=t;
int tmp=a[s];
if(s<t){
while(i<j){
while(i<j&&a[j]>=tmp)
j--;
a[i]=a[j];
while(i<j&&a[i]<=tmp)
i++;
a[j]=a[i];
}
a[i]=tmp;
quick_sort(a,s,i-1);
quick_sort(a,i+1,t);
}
}
用cmp对结构排序中如果遇到字符串的比较用strcmp()
eg:
typedef struct hotell
{
char id[25];
int sum;
}HHH;
bool cmp(HHH a,HHH b)
{
return a.sum==b.sum ? strcmp(a.id,b.id)<0?1:0 : a.sum>b.sum;
}
##enen
因为刚开始用的全局变量写的,后又写了非全局变量,明显非全局变量适用范围更广