#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);
quicksort_linklist(begin, p1);
quicksort_linklist(p1->next, end);
}
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;
ListNode *head = &a;
cout << "单链表快排:" << endl;
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
quicksort_linklist(&a, &g);
head = &a;
while (head) {
cout << head->val << " ";
head = head->next;
}
return 0;
}