快速排序

  • 记录一下数组和单链表的快速排序
#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; 
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值