c++排序算法

排序算法

  • 冒泡排序(Bubble Sort)
    • 原理:重复地走访过要排序的数列,一次比较两个元素,如果它们的顺序错误就把它们交换过来。走访数列的工作是重复地进行直到没有再需要交换,也就是说该数列已经排序完成。
    • 示例代码
      #include <iostream>
      #include <vector>
      
      void bubbleSort(std::vector<int>& arr) {
          int n = arr.size();
          for (int i = 0; i < n - 1; ++i) {
              for (int j = 0; j < n - i - 1; ++j) {
                  if (arr[j] > arr[j + 1]) {
                      std::swap(arr[j], arr[j + 1]);
                  }
              }
          }
      }
      
      int main() {
          std::vector<int> arr = {64, 34, 25, 12, 22, 11, 90};
          bubbleSort(arr);
          for (int num : arr) {
              std::cout << num << " ";
          }
          std::cout << std::endl;
          return 0;
      }

    • 快速排序(Quick Sort)
      • 原理:选择一个基准值,将数组分为两部分,使得左边部分的所有元素都小于等于基准值,右边部分的所有元素都大于等于基准值,然后分别对左右两部分递归地进行排序。
    • 示例代码
      #include <iostream>
      #include <vector>
      
      int partition(std::vector<int>& arr, int low, int high) {
          int pivot = arr[high];
          int i = low - 1;
          for (int j = low; j < high; ++j) {
              if (arr[j] < pivot) {
                  ++i;
                  std::swap(arr[i], arr[j]);
              }
          }
          std::swap(arr[i + 1], arr[high]);
          return i + 1;
      }
      
      void quickSort(std::vector<int>& arr, int low, int high) {
          if (low < high) {
              int pi = partition(arr, low, high);
              quickSort(arr, low, pi - 1);
              quickSort(arr, pi + 1, high);
          }
      }
      
      int main() {
          std::vector<int> arr = {64, 34, 25, 12, 22, 11, 90};
          int n = arr.size();
          quickSort(arr, 0, n - 1);
          for (int num : arr) {
              std::cout << num << " ";
          }
          std::cout << std::endl;
          return 0;
      }

    • 搜索算法

    • 二分查找(Binary Search)
      • 原理:在有序数组中,每次将搜索区间缩小一半,直到找到目标元素或确定目标元素不存在。
      • 示例代码
    • #include <iostream>
      #include <vector>
      
      int binarySearch(const std::vector<int>& arr, int target) {
          int left = 0, right = arr.size() - 1;
          while (left <= right) {
              int mid = left + (right - left) / 2;
              if (arr[mid] == target) {
                  return mid;
              } else if (arr[mid] < target) {
                  left = mid + 1;
              } else {
                  right = mid - 1;
              }
          }
          return -1;
      }
      
      int main() {
          std::vector<int> arr = {1, 2, 3, 4, 5, 6, 7};
          int target = 4;
          int result = binarySearch(arr, target);
          if (result != -1) {
              std::cout << "Element found at index " << result << std::endl;
          } else {
              std::cout << "Element not found" << std::endl;
          }
          return 0;
      }
      

    • 图算法

    • 迪杰斯特拉算法(Dijkstra's Algorithm)
      • 原理:用于求解带权有向图或无向图中单个源节点到其他所有节点的最短路径问题,要求图中所有边的权值非负。
      • 示例代码(使用优先队列优化)
    • #include <iostream>
      #include <vector>
      #include <queue>
      #include <limits>
      
      using namespace std;
      
      const int INF = numeric_limits<int>::max();
      
      vector<int> dijkstra(const vector<vector<pair<int, int>>>& graph, int start) {
          int n = graph.size();
          vector<int> dist(n, INF);
          dist[start] = 0;
          priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
          pq.push({0, start});
          while (!pq.empty()) {
              int u = pq.top().second;
              int d = pq.top().first;
              pq.pop();
              if (d > dist[u]) continue;
              for (const auto& edge : graph[u]) {
                  int v = edge.first;
                  int weight = edge.second;
                  if (dist[u] + weight < dist[v]) {
                      dist[v] = dist[u] + weight;
                      pq.push({dist[v], v});
                  }
              }
          }
          return dist;
      }
      
      int main() {
          int n = 5;
          vector<vector<pair<int, int>>> graph(n);
          graph[0].emplace_back(1, 4);
          graph[0].emplace_back(2, 2);
          graph[1].emplace_back(2, 5);
          graph[1].emplace_back(3, 10);
          graph[2].emplace_back(3, 3);
          graph[3].emplace_back(4, 7);
          vector<int> dist = dijkstra(graph, 0);
          for (int i = 0; i < n; ++i) {
              cout << "Distance from node 0 to node " << i << " is " << dist[i] << endl;
          }
          return 0;
      }
      

    • 动态规划算法

    • 斐波那契数列(Fibonacci Sequence)
      • 原理:斐波那契数列是指这样一个数列:0、1、1、2、3、5、8、13、21、34、…… ,在数学上,斐波那契数列以如下递推的方法定义:F(0)=0,F(1)=1, F(n)=F(n−1)+F(n−2)(n≥2,n∈N∗)。可以使用动态规划的思想来避免重复计算。
      • 示例代码
    • #include <iostream>
      #include <vector>
      
      int fibonacci(int n) {
          if (n == 0) return 0;
          if (n == 1) return 1;
          std::vector<int> dp(n + 1);
          dp[0] = 0;
          dp[1] = 1;
          for (int i = 2; i <= n; ++i) {
              dp[i] = dp[i - 1] + dp[i - 2];
          }
          return dp[n];
      }
      
      int main() {
          int n = 10;
          std::cout << "Fibonacci number at position " << n << " is " << fibonacci(n) << std::endl;
          return 0;
      }
      

字符串处理算法

  • KMP 算法(Knuth-Morris-Pratt Algorithm)
    • 原理:用于在一个主字符串 text 中查找子字符串 pattern 的出现位置。它通过预处理 pattern 构建一个部分匹配表(也称为失配函数),利用这个表在匹配过程中避免不必要的回溯,从而将时间复杂度优化到 O(n+m),其中 n 是 text 的长度,m 是 pattern 的长度。
    • 示例代码
#include <iostream>
#include <vector>
#include <string>

// 构建部分匹配表
std::vector<int> computeLPSArray(const std::string& pattern) {
    int m = pattern.length();
    std::vector<int> lps(m, 0);
    int len = 0;
    int i = 1;
    while (i < m) {
        if (pattern[i] == pattern[len]) {
            len++;
            lps[i] = len;
            i++;
        } else {
            if (len != 0) {
                len = lps[len - 1];
            } else {
                lps[i] = 0;
                i++;
            }
        }
    }
    return lps;
}

// KMP 搜索算法
std::vector<int> KMPSearch(const std::string& text, const std::string& pattern) {
    int n = text.length();
    int m = pattern.length();
    std::vector<int> lps = computeLPSArray(pattern);
    std::vector<int> indices;
    int i = 0;
    int j = 0;
    while (i < n) {
        if (pattern[j] == text[i]) {
            j++;
            i++;
        }
        if (j == m) {
            indices.push_back(i - j);
            j = lps[j - 1];
        } else if (i < n && pattern[j] != text[i]) {
            if (j != 0) {
                j = lps[j - 1];
            } else {
                i++;
            }
        }
    }
    return indices;
}

int main() {
    std::string text = "ABABDABACDABABCABAB";
    std::string pattern = "ABABCABAB";
    std::vector<int> indices = KMPSearch(text, pattern);
    if (indices.empty()) {
        std::cout << "Pattern not found." << std::endl;
    } else {
        for (int index : indices) {
            std::cout << "Pattern found at index " << index << std::endl;
        }
    }
    return 0;
}

贪心算法

  • 哈夫曼编码(Huffman Coding)
    • 原理:一种用于无损数据压缩的算法。它通过构建哈夫曼树,将出现频率高的字符用较短的编码表示,出现频率低的字符用较长的编码表示,从而实现数据的压缩。
    • 示例代码
#include <iostream>
#include <queue>
#include <vector>
#include <string>

// 哈夫曼树节点结构
struct HuffmanNode {
    char data;
    int freq;
    HuffmanNode *left, *right;

    HuffmanNode(char data, int freq) : data(data), freq(freq), left(nullptr), right(nullptr) {}
};

// 用于优先队列的比较函数
struct compare {
    bool operator()(HuffmanNode* l, HuffmanNode* r) {
        return l->freq > r->freq;
    }
};

// 构建哈夫曼树
HuffmanNode* buildHuffmanTree(const std::vector<char>& data, const std::vector<int>& freq) {
    int n = data.size();
    std::priority_queue<HuffmanNode*, std::vector<HuffmanNode*>, compare> minHeap;
    for (int i = 0; i < n; ++i) {
        minHeap.push(new HuffmanNode(data[i], freq[i]));
    }
    while (minHeap.size() != 1) {
        HuffmanNode* left = minHeap.top();
        minHeap.pop();
        HuffmanNode* right = minHeap.top();
        minHeap.pop();
        HuffmanNode* top = new HuffmanNode('$', left->freq + right->freq);
        top->left = left;
        top->right = right;
        minHeap.push(top);
    }
    return minHeap.top();
}

// 打印哈夫曼编码
void printCodes(HuffmanNode* root, std::string str) {
    if (!root) return;
    if (!root->left && !root->right) {
        std::cout << root->data << ": " << str << std::endl;
    }
    printCodes(root->left, str + "0");
    printCodes(root->right, str + "1");
}

// 哈夫曼编码主函数
void HuffmanCodes(const std::vector<char>& data, const std::vector<int>& freq) {
    HuffmanNode* root = buildHuffmanTree(data, freq);
    printCodes(root, "");
}

int main() {
    std::vector<char> arr = {'a', 'b', 'c', 'd', 'e', 'f'};
    std::vector<int> freq = {5, 9, 12, 13, 16, 45};
    HuffmanCodes(arr, freq);
    return 0;
}

几何算法

  • 凸包算法(Graham Scan)
    • 原理:用于求解给定平面上一组点的凸包,即包含所有这些点的最小凸多边形。Graham Scan 算法首先找到最左下角的点作为基准点,然后按照极角对其他点进行排序,最后使用栈来构建凸包。
    • 示例代码
#include <iostream>
#include <vector>
#include <algorithm>

struct Point {
    int x, y;
};

// 用于比较点的极角
int orientation(Point p, Point q, Point r) {
    int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
    if (val == 0) return 0;
    return (val > 0) ? 1 : 2;
}

// Graham Scan 算法
std::vector<Point> convexHull(std::vector<Point> points) {
    int n = points.size();
    if (n < 3) return {};
    int ymin = points[0].y, min = 0;
    for (int i = 1; i < n; i++) {
        int y = points[i].y;
        if ((y < ymin) || (ymin == y && points[i].x < points[min].x)) {
            ymin = points[i].y;
            min = i;
        }
    }
    std::swap(points[0], points[min]);
    std::sort(points.begin() + 1, points.end(), [&](const Point& p1, const Point& p2) {
        int o = orientation(points[0], p1, p2);
        if (o == 0) {
            return ((p1.x - points[0].x) * (p1.x - points[0].x) + (p1.y - points[0].y) * (p1.y - points[0].y)) <
                   ((p2.x - points[0].x) * (p2.x - points[0].x) + (p2.y - points[0].y) * (p2.y - points[0].y));
        }
        return o == 2;
    });
    std::vector<Point> hull;
    hull.push_back(points[0]);
    hull.push_back(points[1]);
    for (int i = 2; i < n; i++) {
        while (hull.size() >= 2 && orientation(hull[hull.size() - 2], hull[hull.size() - 1], points[i]) != 2) {
            hull.pop_back();
        }
        hull.push_back(points[i]);
    }
    return hull;
}

int main() {
    std::vector<Point> points = {{0, 3}, {1, 1}, {2, 2}, {4, 4}, {0, 0}, {1, 2}, {3, 1}, {3, 3}};
    std::vector<Point> hull = convexHull(points);
    for (const auto& point : hull) {
        std::cout << "(" << point.x << ", " << point.y << ")" << std::endl;
    }
    return 0;
}
希望这些代码能帮助您理解并解决这个问题,如果有问题,请随时提问。
  蒟蒻题解,神犇勿喷,点个赞再走吧!QAQ

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值