排序总结

快排源码:

时间复杂度:最好:nlogn;最差:n*n

逻辑:

1. i,j为开始和结束的阈值,设置a[i]为基线,赋值为key,即key=a[0];

2. j--递减,一直到出现a[j]小于key,然后交换a[i]和a[j]。

3. i++增加,一直到出现a[i]大于key,然后交换a[i]和a[j]。

4.重复2,3.

void quickSort(int[] a, int start, int end) {
  int key = a[start]
  int start_index = start;
  int end_index = end;
  while (start <= end) {
    if (start == end) {
      break;
    }
    while (a[end] >= key) {
      end--;
    }
    swap(a[end],a[start]);
    start++;
    while (a[start] <= key) {
      start++;
    }
    swap(a[start],a[end]);
    end--;
  }
  quickSort(a, start_index, start);
  quickSort(a, start, end_index);
}

合并排序:

思想:动态规划,先每个进行排序,然后进行两组两组的合并。

void mergeSort(int a[], int start, int end, int result[]) {
  if (start >= end) {
    return;
  }
  if (start == end - 1) {
    swapbysort(a[start], a[end]);
  } else {
    int mid = ( start + end ) / 2;
    mergeSort (a, start, mid, result);
    mergeSort (a, mid+1, end, result);
    merge(a, start, mid, end, result);
  }
}
void merge(int a[], int start,int mid, int end, int result[]) {
  int start_index = start;
  int end_index = mid + 1;
  for (int i = start; i <= end; i++) {
    if (start_index > mid) {
      result[i] = a[end_index++];break;    
    }
    if (end_index > end) {
      result[i] = a[start_index++];break;
    }
    if (a[start_index] >= a [end_index]){
      result[i] = a[start_index++];
    } else {
      result[i] = a[end_index++];
    }
  }
  for (int i = start; i <= end; i++) {
    result[i] = a[i]; 
  }
}

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值