快速排序:
#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);
}