zoukankan      html  css  js  c++  java
  • 归并排序

     1 /**
     2  * 排序算法之归并排序
     3  */
     4 #include <iostream>
     5 #include <vector>
     6 using namespace std;
     7 
     8 void mergeKP(vector<int>& vec, int l1, int r1, int l2, int r2) {
     9     int i = l1;
    10     int j = l2;
    11     int n = (r1 - l1 + 1) + (r2 - l2 + 1);
    12 
    13     vector<int> temp(n);
    14     int k = 0;
    15     while (i <= r1 && j <= r2) {
    16         if (vec[i] < vec[j]) {
    17             temp[k++] = vec[i++];
    18         } else {
    19             temp[k++] = vec[j++];
    20         }
    21     }
    22     while (i <= r1) {
    23         temp[k++] = vec[i++];
    24     }
    25     while (j <= r2) {
    26         temp[k++] = vec[j++];
    27     }
    28     for (int i = 0; i < n; i++) {
    29         vec[l1 + i] = temp[i];
    30     }
    31 }
    32 
    33 void sortGuiBing(vector<int>& vec,int start, int end) {
    34     if (start < end) {
    35         int mid = (start + end) / 2;
    36         sortGuiBing(vec, start, mid);
    37         sortGuiBing(vec, mid + 1, end);
    38         mergeKP(vec, start, mid, mid + 1, end);
    39     }
    40 }
    41 int main() {
    42     vector<int> vec = {2,1,3,5,4};
    43     int len = vec.size();
    44     sortGuiBing(vec, 0, len - 1);
    45     for (int i = 0; i < len; ++i) {
    46         cout << vec[i] << endl;
    47     }
    48     return 0;
    49 }
  • 相关阅读:
    mysql数据库启动停止
    事务的隔离级别
    排序之选择排序
    排序之希尔排序
    排序之折半插入排序
    排序之直接插入排序
    排序之冒泡排序
    排序之快速排序
    字符串拷贝和拼接
    字符串旋转问题
  • 原文地址:https://www.cnblogs.com/gousheng/p/8522179.html
Copyright © 2011-2022 走看看