![](https://i-blog.csdnimg.cn/blog_migrate/8a9102f5e43e8850e01b6cd310443fd4.webp?x-image-process=image/format,png)
void BubbleSort(int a[], int n) {
for (int i = 0; i <n; i++) {
for (int j = 0; j < n-i-1 ; j++) {
if (a[j] > a[j+1])
swap(a[j], a[j+1]);
}
}
}
void InsertSort(int a[],int n){
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(a[i]<a[j]) {
swap(a[i],a[j]);
}
}
}
}
- 选择排序
void InsertSort(int a[], int n) {
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (a[i] < a[j]) {
swap(a[i], a[j]);
}
}
}
}
- 希尔排序
void ShellSort(int a[], int n) {
int temp, gap = n / 2;
while (gap > 0) {
for (int i = gap; i < n; i++) {
temp = a[i];
int preIndex = i - gap;
while (preIndex >= 0 && a[preIndex] > temp) {
a[preIndex + gap] = a[preIndex];
preIndex -= gap;
}
a[preIndex + gap] = temp;
}
gap /= 2;
}
}
- 堆排序
void AdjustHeap(int a[], int i, int length) {
int temp = a[i];
for (int k = 2 * i + 1; k < length; k = 2 * k + 1) {
if (k + 1 < length&&a[k] < a[k + 1]) {
k++;
}
if (a[k] > temp) {
a[i] = a[k];
i = k;
}
else {
break;
}
}
a[i] = temp;
}
void HeapSort(int a[], int n) {
for (int i = n / 2 - 1; i >= 0; i--) {
AdjustHeap(a, i, n);
}
for (int j = n - 1; j >= 0; j--) {
swap(a[0], a[j]);
AdjustHeap(a, 0, j);
}
}
- 快速排序
void QuickSort(int a[],int start,int end){
if(start>=end)return;
int i=start,j=end;
int base=a[i];
while(i<j){
while(a[j]>base&&i<j){
j--;
}
if(i<j){
swap(a[i],a[j]);
i++;
}
while(a[i]<base&&i<j){
i++;
}
if(i<j){
swap(a[i],a[j]);
j--;
}
}
a[i]=base;
QuickSort(a,start,i-1);
QuickSort(a,i+1,end);
}
- 归并排序