# 快速排序

• 记录一下数组和单链表的快速排序
#include <stdio.h>
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>
#include <algorithm>

using namespace std;

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

struct BSTNode {
int val;
int count;
BSTNode *left;
BSTNode *right;
BSTNode(int x) : val(x), count(0), left(NULL), right(NULL) {}
};

struct GraphNode {
int label;
vector<GraphNode*> neighbors;
GraphNode(int x) : label(x) {};
};

void quicksort(vector<int> &nums, int left, int right) {
if (left > right) {
return;
}

int temp = nums[left];
int i = left;
int j = right;

while (i != j) {
while (i < j && nums[j] >= temp)
{
j--;
}

while (i < j && nums[i] <= temp) {
i++;
}

if (i < j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
}

//基准归位
nums[left] = nums[i];
nums[i] = temp;

quicksort(nums, left, i - 1);
quicksort(nums, i + 1, right);
}

void swap(int &a, int &b) {
int t = a;
a = b;
b = t;
}

void quicksort_linklist(ListNode *begin, ListNode *end) {

if (begin == NULL || end == NULL || begin == end) {
return;
}

ListNode *p1 = begin;
ListNode *p2 = begin->next;
int temp = begin->val;

while (p2 != NULL) {
if (p2->val < temp)
{
p1 = p1->next;
if (p1 != p2) {
swap(p1->val, p2->val);
}
}
p2 = p2->next;
}

swap(p1->val, begin->val);
}

int main() {

vector<int> nums = { 3,6,8,2,7,9,1 };
cout << "数组快排:" << endl;
for (auto num : nums) {
cout << num << " ";
}

cout << endl;

quicksort(nums, 0, nums.size() - 1);

for (auto num : nums) {
cout << num << " ";
}

cout << endl;

ListNode a(8);
ListNode b(3);
ListNode c(7);
ListNode d(4);
ListNode e(5);
ListNode f(6);
ListNode g(9);

a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
e.next = &f;
f.next = &g;

cout << "单链表快排:" << endl;

cout << head->val << " ";
}

cout << endl;

cout << head->val << " ";
}

return 0;
}


• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 打赏

打赏

梦醒时分1218

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 举报
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文

03-13 3032
03-04 1万+
09-10 49万+
08-13 64万+
06-12 14万+
07-02 26万+
11-29 16万+
03-05 7万+
01-29 6万+
07-01 7万+
01-11 11万+
10-08 2万+
02-07 475