一、快排
// ConsoleApplication1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;
void sort(vector<int>& v_nums, int left, int right)
{
if (left >= right)
return;
int temp = v_nums[left];
int leftTemp = left;
int rightTemp = right;
while (leftTemp < rightTemp)
{
while (leftTemp < rightTemp&&v_nums[rightTemp] >= temp)
rightTemp--;
if (leftTemp < rightTemp)
{
v_nums[leftTemp] = v_nums[rightTemp];
leftTemp++;
}
while (leftTemp < rightTemp&&v_nums[leftTemp] <= temp)
leftTemp++;
if (leftTemp < rightTemp)
{
v_nums[rightTemp] = v_nums[leftTemp];
rightTemp--;
}
}
v_nums[leftTemp] = temp;
sort(v_nums, left, leftTemp - 1);
sort(v_nums, leftTemp + 1, right);
}
int main()
{
vector<int> v_nums;
v_nums.push_back(2);
v_nums.push_back(1);
v_nums.push_back(6);
v_nums.push_back(3);
sort(v_nums, 0, v_nums.size() - 1);
for (int i = 0; i < v_nums.size(); i++)
{
cout << v_nums[i] << endl;
}
system("pause");
return 0;
}
二、冒泡排序:
//冒泡排序
void COrdinarySort::bubbleSort(vector<int>& nums)
{
for (int i = 0; i < nums.size(); ++i)
{
for (int j = i+1; j < nums.size(); ++j)
{
if (nums[j] < nums[i])
{
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
}
}
三、归并排序
//归并排序(左闭右开区间)
void COrdinarySort::mergeSort(vector<int>& nums)
{
sort(nums, 0, nums.size());
}
void COrdinarySort::sort(vector<int>& nums, int left, int right)
{
if ((right-left)<=1)
return;
int mid = left + (right - left)/2;
sort(nums, left, mid);
sort(nums, mid, right);
merge(nums, left, right,mid);
}
void COrdinarySort::merge(vector<int>& nums, int left, int right,int mid)
{
if (left >= right)
return;
vector<int> leftNums(nums.begin() + left, nums.begin() + mid);
vector<int> rightNums(nums.begin() + mid, nums.begin() + right);
int i = 0;
int j = 0;
while (i<leftNums.size()&&j<rightNums.size())
{
if (leftNums[i] <= rightNums[j])
{
nums[left] = leftNums[i];
i++;
left++;
}
else
{
nums[left] = rightNums[j];
j++;
left++;
}
}
while (i < leftNums.size())
{
nums[left] = leftNums[i];
i++;
left++;
}
while (j < rightNums.size())
{
nums[left] = rightNums[j];
j++;
left++;
}
}
四、插入排序
//插入排序
void COrdinarySort::insertSort(vector& nums)
{
vector v_temp = nums;
for (int i = 0; i < v_temp.size(); i++)
{
int j = i - 1;
while (j >= 0)
{
if (v_temp[i] < nums[j])
{
nums[j + 1] = nums[j];
}
else
{
break;
}
--j;
}
nums[j + 1] = v_temp[i];
}
}
五、堆排序
//堆排序
void COrdinarySort::heapify(int arr[], int n, int i)
{
int largest = i;
int lson = 2 * i + 1;
int rson = 2 * i + 2;
if (lson < n && arr[largest] < arr[lson])
largest = lson;
if (rson < n && arr[largest] < arr[rson])
largest = rson;
if (largest != i)
{
int temp = arr[i];
arr[i] = arr[largest];
arr[largest] = temp;
heapify(arr, n, largest);
}
}
void COrdinarySort::heapSort(int arr[], int n)
{
for (int i = n/2-1; i >=0; i--)
heapify(arr, n, i);
for (int i = n - 1; i > 0; i--)
{
int temp = arr[0];
arr[i] = temp;
arr[0] = arr[i];
heapify(arr, i, 0);
}
}