归并排序:
代码写的比较水: 根据别人写的
想看详细的请看这里: https://blog.csdn.net/yuehailin/article/details/68961304
#include<cstdio>
using namespace std;
void GB_qsort(int a[],int first,int mid,int last,int temp[]) {
int n=mid,m=last;
int k=0;
int i=first,j=mid+1;
while(i<=n && j<=m) {
if(a[i]<=a[j]) // 比较 如果哪个小 就把哪个先赋给temp[]
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}
while(i<=n) // 如果上面比较完数组还有数字,那么肯定是全部大于数组的最后一个的, 直接全部赋给数组
temp[k++]=a[i++];
while(j<=m)
temp[k++]=a[j++];
for(i=0; i<k; i++){
a[first+i]=temp[i];
}
}
void GB_sort(int a[],int first,int last,int temp[]) {
if(first<last) {
int mid=(first+last)/2;
GB_sort(a,first,mid,temp); // 递归 左边排序 first ~~ mid
GB_sort(a,mid+1,last,temp); // 递归 右边排序 mid+1 ~~ last
GB_qsort(a,first,mid,last,temp); // 排序
}
}
bool sort(int a[],int n) {
int *p =new int [n]; // 申请空间 大小 为原来的数组
if(p==NULL) { // 如果n==0 那么肯定NULL 所以false
return false;
} else {
GB_sort(a,0,n-1,p); // n-1; 数组最后一个数字的实际下标
delete[] p;
return true;
}
}
int main() {
int a[10]= {8,5,2,9,7,6,4,1,3,0};
int i;
sort(a,10);
for(i=0; i<10; i++) {
printf("%d ",a[i]);
}
return 0;
}