冒泡法进行升序排序,双向冒泡法进行降序排序。
#include <stdio.h>
#include <stdlib.h>
void rndData(int data[], int length){
int i;
for(i=0;i<length;i++){
data[i] = rand()% 100 + 1;//[1, 100]
}
}
void printData(int data[], int length){
int i;
for(i=0;i<length;i++){
printf("%4d", data[i]);
if((i+1)%10 == 0){
printf("\n");
}
}
printf("\n");
}
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
void bubbleSort(int data[], int length){
int i,j=length;
while(j>0){
for(i=0;i<j-1;i++){
if(data[i] > data[i+1]){
swap(&data[i], &data[i+1]);
}
}
j--;
}
}
void shakerBubbleSort(int data[], int length){
int left = 0, right = length - 1;
int i,j;
while(right > left){
for(i=left;i<right;i++){
if(data[i] < data[i+1]){
swap(&data[i], &data[i+1]);
j = i;
}
}
right = j;
for(i=right-1;i>=left;i--){
if(data[i] < data[i+1]){
swap(&data[i], &data[i+1]);
j = i + 1;
}
}
left = j;
}
}
void main(){
int data[50];
srand(time(0));
//rand data and sort asc
rndData(data, 50);
printData(data, 50);
bubbleSort(data, 50);
printData(data, 50);
//sort des
//rndData(data, 50);
//printData(data, 50);
shakerBubbleSort(data, 50);
printData(data, 50);
}