#include <stdio.h>
void SortBubble(int array[], int n, int asc);
int main(void){
int array[] = {7,1,6,9,3};
int arraySize = (int)(sizeof(array)/sizeof(array[0]));
SortBubble(array, arraySize, 1);
SortBubble(array, arraySize, 0);
return 0;
}
void SortBubble(int array[], int n, int asc){
int tmp;
for(int i = 0; i < n - 1; i++){
for(int j = 0; j < n - 1; j++){
if(asc) {
//ascending order
if(array[j+1] < array[j]){
//j and j+Swap the first value
tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
}
} else {
//descending order
if(array[j+1] > array[j]){
tmp = array[j];
array[j] = array[j+1];
array[j+1] = tmp;
}
}
}
}
asc
? printf("ascending order:")
: printf("descending order:");
for(int i = 0; i < n; i++){
printf("%d,", array[i]);
}
printf("\n");
}
Numerical flow
When i = 0, turning the loop of j ... 1,7,6,9,3 1,6,7,9,3 1,6,7,9,3 1,6,7,3,9
When i = 1, if you turn the loop of j ... 1,6,7,3,9 1,6,7,3,9 1,6,3,7,9 1,6,3,7,9
. . .
output
Ascending order: 1,3,6,7,9,
Descending order: 9,7,6,3,1,
Recommended Posts