排序模板
普通排序
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, a[105];
cin>>n;
for (int i = 0; i < n; i++)
cin >> a[i];
sort(a,a + n);
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
}
冒泡排序
#include <bits/stdc++.h>
using namespace std;
int n, a[105];
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
cin >> a[i];
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (a[j] > a[j + 1])
swap(a[j], a[j + 1]);
}
}
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
}
选择排序
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
int arr[105];
cin >> n;
for (int i = 0; i < n; i++)
cin >> arr[i];
for (int i = 0; i < n - 1; i++)
{
int min = i;
for (int j = i; j < n; j++)
{
if (arr[min] > arr[j])
{
min = j;
}
}
if (min != i)
{
swap(arr[i], arr[min]);
}
}
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
插入排序
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n, a[105];
cin>>n;
for (int i = 0; i < n; i++)
cin >> a[i];
int i, j, temp;
for (i = 1; i < n; i++)
{
temp = a[i];
for (j = i; j > 0 && temp < a[j - 1]; j--)
a[j] = a[j - 1];
a[j] = temp;
}
for (int i = 0; i < n; i++)
cout << a[i] << " ";
return 0;
}
快速排序
#include <iostream>
using namespace std;
void QuickSort(int array[], int low, int high) {
int i = low;
int j = high;
if(i >= j)
return;
int temp = array[low];
while(i != j) {
while(array[j] >= temp && i < j)
j--;
while(array[i] <= temp && i < j)
i++;
if(i < j)
swap(array[i], array[j]);
}
swap(array[low], array[i]);
QuickSort(array, low, i - 1);
QuickSort(array, i + 1, high);
}
int main()
{
int n, a[105];
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
QuickSort(a, 1, n);
for (int i = 1; i <= n; i++)
cout << a[i] << " ";
}