数据结构算法-快排和归并

1.快排

#include <stdio.h>
/*//j从0开始保存比arr[right]小的值.12543->12354*/
//分区
int Partition(int array[], int left, int right){
int i,j;
int temp;
j=left-1;
for(i=left;i<=right;i++){
if(array[i]<=array[right]){
j++;
temp=array[j];
array[j]=array[i];
array[i]=temp;
}
}
return j;
}
void QuickSort(int arr[],int left,int right){
int pivot;
if(left<right){
pivot=Partition(arr,left,right);
QuickSort(arr,left,pivot-1);
QuickSort(arr,pivot+1,right);
}
}
void main(){
int test;
int arr[]={2,4,3,1,5};
QuickSort(arr,0,4);
int i;
for (i = 0; i < 5; ++i)
{
printf("%d\t", arr[i]);
}
}
 


2.归并排序

#include <stdio.h>
//开始这三行用来举测试用例的
//10 9 7 6 2 | 4 3 1 5 0 |.....
//合并
void Merge(int arr[],int tempArr[],int low,int mid ,int high){
int i=low,j=mid+1;
int k=low;
while(i<=mid&&j<=high){//两个数组遍历比较
if(arr[i]<arr[j]){
tempArr[k++]=arr[i++];
}else{
tempArr[k++]=arr[j++];
}
}
while(i<=mid){
tempArr[k++]=arr[i++];
}
while(j<=high){
tempArr[k++]=arr[j++];
}
for(i=low;i<=high;i++){
arr[i++]=tempArr[i++];
}
}
//递归调用合并
void MergeSort(int arr[],int tempArr[],int low,int high){
int mid;
if(low<high){
mid=(low+high)/2;
MergeSort(arr,tempArr,low,mid);
MergeSort(arr,tempArr,mid+1,high);
Merge(arr,tempArr,low,mid,high);
}
}
int main(){
int a[8] = {50, 10, 20, 30, 70, 40, 80, 60};
    int i, b[8];
    MergeSort(a, b, 0, 7);
    for(i=0; i<8; i++)
        printf("%d ", a[i]);
    printf("\n");
    return 0;
}


 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值