排序

本文详细介绍了两种高效的排序算法:快速排序和归并排序。快速排序通过分治法将数组分为较小和较大元素的子数组进行递归排序;归并排序则采用自上而下的合并策略,将两个已排序的子数组合并为一个有序数组。通过实例演示了排序过程,展示了算法的高效性和稳定性。

快速排序

void QuickSort(int r[], int low, int high){
  int pos;
  if(low < high){
    pos = partition(r, low, high);
    QuickSort(r, low, pos-1);
    QuickSort(r, pos+1, high);
  }  
}
int partition(int r, int i, int j){
  int pivot = r[i];
  while(i<j){
    while(r[j] > pivot){
      j--;
    }
    if(i<j)
      r[i++] = r[j];

    while(r[i] < pivot){
      i++;
    }
    if(i<j)
      r[j--]=r[i];
  }
  r[i] = pivot;
  return i;
}

归并排序

#include <stdlib.h>
#include <stdio.h>
 
void Merge(int sourceArr[],int tempArr[], int startIndex, int midIndex, int endIndex)
{
    int i = startIndex, j=midIndex+1, k = startIndex;
    while(i!=midIndex+1 && j!=endIndex+1)
    {
        if(sourceArr[i] > sourceArr[j])
            tempArr[k++] = sourceArr[j++];
        else
            tempArr[k++] = sourceArr[i++];
    }
    while(i != midIndex+1)
        tempArr[k++] = sourceArr[i++];
    while(j != endIndex+1)
        tempArr[k++] = sourceArr[j++];
    for(i=startIndex; i<=endIndex; i++)
        sourceArr[i] = tempArr[i];
}
 
//内部使用递归
void MergeSort(int sourceArr[], int tempArr[], int startIndex, int endIndex)
{
    int midIndex;
    if(startIndex < endIndex)
    {
        midIndex = (startIndex + endIndex) / 2;
        MergeSort(sourceArr, tempArr, startIndex, midIndex);
        MergeSort(sourceArr, tempArr, midIndex+1, endIndex);
        Merge(sourceArr, tempArr, startIndex, midIndex, endIndex);
    }
}
 
int main(int argc, char * argv[])
{
    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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值