|
CS256 - Principles of Structured Design
Fall 2021
|
Displaying ./code/cs256su21code/sorts/bubbleSort.c
/*
A demonstration of Bubble Sort
This is the simplest sorting algorithm, it works by repeatedly
swapping adjacent elements if they are in the wrong order.
Here, Bubble Sort takes in two arguments: the array, and the size.
this is just a demonstration file, where you input a number,
and it'll create an array with that many elements, and also
generate that number of random numbers.
*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 1048576
void bubbleSort(int arr[], int size);
void swap(int *x, int *y);
int main(int argc, char *argv[]){
if(argc < 2){
fprintf(stderr, "Usage: %s <number>\n", argv[0]);
exit(1);
}
int sz = atoi(argv[1]);
if(sz > MAX || sz < 1){
fprintf(stderr, "Error: This value is not allowed\n");
exit(1);
}
int arr[sz];
time_t t;
/* Intializes random number generator */
srand((unsigned) time(&t)); //seeding it to the computers clock
for(int i = 0; i < sz; i++){
arr[i] = rand() % sz; //generating an array of random numbers
}
bubbleSort(arr, sz);
return 0;
}
void bubbleSort(int arr[], int size){
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;
}
|