113 lines
1.5 KiB
Markdown
113 lines
1.5 KiB
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;
|
|
}
|
|
|
|
```
|
|
|
|
|
|
|
|
### 插入排序
|
|
|
|
```c
|
|
#include <stdio.h>
|
|
|
|
void insertSort(int *a, int n, int flag){
|
|
int i, j, t;
|
|
for(i=1;i<n;i++){//假设前i位已经有序
|
|
t = a[i];//备份当前需要排序的数
|
|
j=i-1;//计算出当前位置前一项
|
|
while((flag>0?a[j] > t:a[j] < t) && j>=0) {
|
|
a[j+1] = a[j];
|
|
j--;
|
|
}
|
|
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;
|
|
insertSort(a, n, 0);
|
|
printArray(a, n);
|
|
|
|
return 0;
|
|
}
|
|
|
|
``` |