以下算法均按从小到大排序。
1、快排
#include
using namespace std;
void QuikSort(int a[], int l, int r){
if(l >= r) return;
int key = a[l];
int i = l, j = r;
while(i < j){
while(i < j && a[j] > key) j--;
while(i < j && a[i] <= key) i++;
if(i < j) swap(a[i], a[j]);
}
swap(a[l], a[j]);
QuikSort(a, l, j);
QuikSort(a, j+1, r);
}
int main(){
// int a[] = {19,5,3,674,84,85,4,90,6,34};
// int a[] = {9,8,7,6,5,4,3,2,1};
// int a[] = {1,2,3,4,5,6,7,8,9};
int a[] = {5,4,6,1,7,8,2,3,9};
int n = 9;
QuikSort(a, 0, n-1);
for(int i = 0; i < n; i++)
cout<
2、归并
#include
#include
using namespace std;
void MergeSort(int a[], int l, int r){
if(l == r) return;
int mid = (l+r) >> 1;
MergeSort(a, l, mid);
MergeSort(a, mid+1, r);
vector tmp;
int i = l, j = mid+1;
while(i <= mid && j <= r){
if(a[i] <= a[j]) tmp.push_back(a[i++]);
else tmp.push_back(a[j++]);
}
while(i <= mid) tmp.push_back(a[i++]);
while(j <= r) tmp.push_back(a[j++]);
for(int k = 0; k < tmp.size(); k++)
a[l++] = tmp[k];
}
int main(){
// int a[] = {19,5,3,674,84,85,4,90,6,34};
// int a[] = {9,8,7,6,5,4,3,2,1};
// int a[] = {1,2,3,4,5,6,7,8,9};
int a[] = {5,4,6,1,7,8,2,3,9};
int n = 9;
MergeSort(a, 0, n-1);
for(int i = 0; i < n; i++)
cout<
3、堆排
注意:为了用数组方便模拟建树,将数组下标从1开始
#include
#include
using namespace std;
void HeapAdjust(int a[], int idx, int mx){
int val = a[idx];
for(int j = 2*idx; j <= mx; j*=2){
if(j < mx && a[j] < a[j+1]) j++;
if(val > a[j]) break;;
a[idx] = a[j], idx = j;
}
a[idx] = val;
}
void HeapSort(int a[], int n){
if(n <= 1) return;
for(int i = n>>1; i >= 1; i--){
HeapAdjust(a, i, n);
}
for(int i = n; i >=1; i--){
swap(a[i], a[1]);
HeapAdjust(a, 1, i-1);
}
}
int main(){
// int a[] = {0,19,5,3,674,84,85,4,90,6,34};
// int a[] = {0,9,8,7,6,5,4,3,2,1};
// int a[] = {0,1,2,3,4,5,6,7,8,9};
int a[] = {0,5,4,6,1,7,8,2,3,9};
int n = 9;
HeapSort(a, n);
for(int i = 1; i <= n; i++)
cout<
4、冒泡
void BubbleSort(int a[], int n){
for(int i = 1; i < n; i++){
int flag = false;
for(int j = 0; j < n-i; j++){
if(a[j] > a[j+1]){
swap(a[j], a[j+1]);
flag = true;
}
}
if(!flag)break;
}
}
5、选择
void SelectionSort(int a[], int n){
for(int i = 0; i < n-1; i++){
int idx = i;
for(int j = i+1; j < n; j++){
if(a[idx] > a[j])
idx = j;
}
swap(a[idx], a[i]);
}
}
6、插入
void InsertionSort(int a[], int n){
for(int i = 1; i < n; i++){
int tmp = a[i];
int j = i-1;
while(j >= 0 && tmp < a[j]){
a[j+1] = a[j];
j--;
}
a[j+1] = tmp;
}
}