排序(ACM模式)冒泡选择插入快排
Posted 久病成良医
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了排序(ACM模式)冒泡选择插入快排相关的知识,希望对你有一定的参考价值。
1. 冒泡
#include <iostream>
#include <vector>
using namespace std;
void print(vector<int>&nums)
{
for (auto i : nums)
cout << i << " ";
cout << endl;
}
void bubblesort(vector<int>&nums, int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (nums[j] > nums[j + 1])
swap(nums[j+1],nums[j]);
}
}
}
int main()
{
int n;
cin >> n;
vector<int> nums; //vector<int> nums(n);写成这样会出错
int temp;
for (int i = 0; i < n; i++)
{
cin >> temp;
nums.push_back(temp);
}
bubblesort(nums, n);
print(nums);
return 0;
}
2. 选择
#include <iostream>
#include <vector>
using namespace std;
void print(vector<int>&nums)
{
for (auto i : nums)
cout << i << " ";
cout << endl;
}
void selectsort(vector<int>&nums, int n)
{
int minindex;
for (int i = 0; i < n; i++)
{
minindex = i;
for (int j = i + 1; j < n; j++)
{
if (nums[j] < nums[minindex])
{
minindex = j;
}
}
swap(nums[i],nums[minindex]);
}
}
int main()
{
int n;
cin >> n;
vector<int>nums;
int temp;
for (int i = 0; i < n; i++)
{
cin >> temp;
nums.push_back(temp);
}
selectsort(nums, n);
print(nums);
return 0;
}
3. 插入
#include <iostream>
#include <vector>
using namespace std;
void print(vector<int>&nums)
{
for (auto i : nums)
cout << i << " ";
cout << endl;
}
void insertsort(vector<int>&nums, int n)
{ //i = 2,要排3个数
for (int i = 0; i < n; i++) //i相当于需要排序的个数 // 5 6 3
{ // 3 6
for (int j = i; j>0; j--) //对i个数进行交换排序 // 3 5 6
{
if (nums[j] < nums[j - 1])
swap(nums[j],nums[j-1]);
}
}
}
int main()
{
int n;
cin >> n;
vector<int>nums;
int temp;
for (int i = 0; i < n; i++)
{
cin >> temp;
nums.push_back(temp);
}
insertsort(nums, n);
print(nums);
return 0;
}
4. 快排
#include <iostream>
#include <vector>
using namespace std;
void print(vector<int>&nums)
{
for (auto i : nums)
cout << i << " ";
cout << endl;
}
void quicksort(vector<int>&nums, int first, int last)
{
if (first >= last) return;
int left = first;
int right = last;
int index = nums[left];
while (left < right&&nums[right] > index)
right--;
if (left < right&&nums[right] < index)
nums[left] = nums[right]; //nums[left++] = nums[right];
while (left < right&&nums[left] <= index)
left++;
if (left<right&&nums[left]>index)
nums[right] = nums[left]; //nums[right--] = nums[left];
nums[left] = index;
quicksort(nums, first, left - 1);
quicksort(nums, left + 1, last);
}
int main()
{
int n;
cin >> n;
vector<int> nums;
int temp;
for (int i = 0; i < n; i++)
{
cin >> temp;
nums.push_back(temp);
}
quicksort(nums, 0, n-1);
print(nums);
return 0;
}
以上是关于排序(ACM模式)冒泡选择插入快排的主要内容,如果未能解决你的问题,请参考以下文章
8种面试经典!排序详解--选择,插入,希尔,冒泡,堆排,3种快排,快排非递归,归并,归并非递归,计数(图+C语言代码+时间复杂度)