|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/jul20/sort.c
#include <stdio.h>
void printArray(int arr[], int size);
void bubbleSort(int arr[], int size);
void swap(int *x, int *y);
int main(){
int arr[] = {5, 1, 3, 7, 9, 4, 6, 2, 8};
printf("--Before Sorting--\n");
printArray(arr, 9);
bubbleSort(arr, 9);
printf("--After Sorting--\n");
printArray(arr, 9);
return 0;
}
void printArray(int arr[], int size){
for(int i = 0; i < size; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
void bubbleSort(int arr[], int size){
if(!arr)
return;
int comps = 0;
int swaps = 0;
for(int i = 0; i < size-1; i++){
for(int j = 0; j < size - i -1;j++){
comps++;
if(arr[j] > arr[j+1]){
swap(&arr[j], &arr[j+1]);
swaps++;
}
}
}
printf("Comparisons: %d, Swaps: %d\n", comps, swaps);
}
void swap(int *x, int *y){
int tmp = *x;
*x = *y;
*y = tmp;
}
|