|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/sorts/bubbleSortBasic.c
/*
A demonstration of BubbleSort
This is the simplest sorting algorithm, it works by repeatedly swapping
adjacent elements if they are in the wrong order.
*/
#include <stdio.h>
void bubbleSort(int arr[], int size);
void swap(int *x, int *y);
void printArray(int arr[], int size);
int main(){
int arr[] = { 5, 1, 3, 7, 9, 4, 6, 2, 8}; //declaring a test array
printf("Before Sort:\n");
printArray(arr, 9);
bubbleSort(arr, 9);
printf("After Sort:\n");
printArray(arr, 9);
return 0;
}
void bubbleSort(int arr[], int size){
if(!arr)
return;
for(int i = 0; i < size-1; i++){
//last elements are already in order
for(int j = 0; j < size-i-1; j++){
if(arr[j] > arr[j+1]){//if the elements adjacent to each other aren't in ascending order
swap(&arr[j], &arr[j+1]);
}
}
}
}
void swap(int *x, int *y){
int tmp = *x;
*x = *y;
*y = tmp;
}
void printArray(int arr[], int size){
for(int i = 0; i < size; i++){
printf("%d ", arr[i]);
}
printf("\n");
}
|