78 lines
1007 B
Markdown
78 lines
1007 B
Markdown
### 冒泡排序
|
|
|
|
```c
|
|
#include <stdio.h>
|
|
|
|
void bubblingSort(int *a, int n, int flag){
|
|
int i, j, t;
|
|
for(i=0;i<n-1;i++){
|
|
for(j=0;j<n-1-i;j++){
|
|
if(flag>0?a[j]>a[j+1]:a[j]<a[j+1]){
|
|
t = a[j];
|
|
a[j] = a[j+1];
|
|
a[j+1] = t;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void printArray(int *a, int n){
|
|
int i;
|
|
for(i=0;i<n;i++){
|
|
printf("%d ", a[i]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
int main(){
|
|
int a[] = {100, 1, 3, 2, 9, -1, 20, 30, 10, 50};
|
|
int n = sizeof(a)/4;
|
|
bubblingSort(a, n, 1);
|
|
printArray(a, n);
|
|
|
|
return 0;
|
|
}
|
|
```
|
|
|
|
|
|
|
|
### 选择排序
|
|
|
|
```c
|
|
#include <stdio.h>
|
|
|
|
void selectSort(int *a, int n, int flag){
|
|
int i, j, t;
|
|
for(i=0;i<n-1;i++){
|
|
for(j=i;j<n;j++){
|
|
if(flag > 0?a[i] > a[j]:a[i] < a[j]){
|
|
t = a[i];
|
|
a[i] = a[j];
|
|
a[j] = t;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void printArray(int *a, int n){
|
|
int i;
|
|
for(i=0;i<n;i++){
|
|
printf("%d ", a[i]);
|
|
}
|
|
printf("\n");
|
|
}
|
|
|
|
int main(){
|
|
int a[] = {100, 1, 3, 2, 9, -1, 20, 30, 10, 50};
|
|
int n = sizeof(a)/4;
|
|
selectSort(a, n, 0);
|
|
printArray(a, n);
|
|
|
|
return 0;
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
### 插入排序 |