| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- //bubble.c
- //famous bubble sort
- //implement the swap algorithm with pointers
- #include <stdio.h>
- #define MAX 9
- //function prototypes
- void printValues();
- void sort();
- void swap(int*, int*);
- int values[] = {7, 3, 9, 4, 6, 1, 2, 8, 5};
- int main(){
- printf("Before: \n");
- printValues();
- sort();
- printf("After: \n");
- printValues();
- return(0);
- } // end main
- // prints values[] by increasing index
- void printValues(){
- printf("[");
- int i = 0;
- for (i = 0; i < MAX; i++){
- printf("%d ", values[i]);
- }
- printf("]\n");
- }
- // implements ascending order bubble sort on values[]
- void sort(){
- int i, j = 0;
- for (i = 0; i < MAX - 1; i++){
- for (j = 0; j < MAX - 1; j++){
- if (values[j] > values [j + 1]){
- swap(&values[j], &values[j + 1]);
- printValues();
- }
- }
- }
- }
- // swap function
- void swap(int* a, int* b){
- int t = 0;
- t = *a;
- *a = *b;
- *b = t;
- }
|