快速排序。冒泡排序递归和非递归的实现

快速排序:
#pragma once
#include <iostream>
#include <stack>
using namespace std;

void QuickSort_Rec(int arr[], int left, int right)
{
	if(left >= right)
	{
		return;
	}
	int end = right;
	int start = left;
	int key = arr[start];
	while (start < end)
	{
		while (start < end && arr[end] >= key)
		{
			--end;
		}
		arr[start] = arr[end];
		while (start < end && arr[start] <= key)
		{
			++start;
		}
		arr[end] = arr[start];
	}

	arr[start] = key;
	QuickSort_Rec(arr, left, start-1);
	QuickSort_Rec(arr, start+1, right);
}

int GetMid(int arr[], int left ,int right)
{
	int key = arr[left];
	while (left < right)
	{
		while (left < right && arr[right] >= key)
		{
			--right;
		}
		arr[left] = arr[right];
		while (left < right && arr[left] <= key)
		{
			++left;
		}
		arr[right] = arr[left];
	}

	arr[left] = key;

	return left;
}

void Quick_Stack(int arr[], int low, int high)
{
	stack<int> s;
	int k = 0;
	if (low < high)
	{
		s.push(low);
		s.push(high);
		while (!s.empty())
		{
			int temp1 = s.top();
			s.pop();
			int temp2 = s.top();
			s.pop();

			k=GetMid(arr, temp2, temp1);

			if(temp2 < k-1)
			{
				s.push(temp2);
				s.push(k-1);
			}
			if (k+1 < temp1)
			{
				s.push(k+1);
				s.push(temp1);
			}
		}
	}
} 

冒泡排序
#pragma once
#include <iostream>


int* bubbleSort(int arr[], int size)
{
	if (size < 2)
		return arr;
	for (int i=0; i<size; i++)
	{
		for(int j=1; j<size-i; j++)
		{
			if(arr[j-1] > arr[j])
			{
				int swp = arr[j];
				arr[j] = arr[j-1];
				arr[j-1] = swp;
			}
		}
	}
	return arr;
}


void bubbleSort_Recursion(int arr[], int size)
{
	if (size < 2)
	{
		return;
	}
	for (int i =1; i<size; i++)
	{
		if (arr[i-1] > arr[i])
		{
			int temp = arr[i];
			arr[i] = arr[i-1];
			arr[i-1] = temp;
		}
	}
	bubbleSort_Recursion(arr, size-1);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值