Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * helpers.c
- *
- * CS50 AP
- * Sort Race
- *
- * Helper functions for the sort race
- */
- #include <cs50.h>
- #include <stdio.h>
- #include "helpers.h"
- /**
- * Returns true if str is a valid flag (-a, -b, -r, or -s), false otherwise.
- */
- bool check_flag(char *str)
- {
- //store the dash and the letter
- char dash = str[0];
- char letter = str[1];
- //return false if there is not a dash
- //return false if the letter doesn't match a, b , r , s
- //return true otherwise
- switch (dash)
- {
- case '-':
- switch (letter)
- {
- case 'a':
- case 'b':
- case 'r':
- case 's':
- return true;
- default:
- return false;
- }
- break;
- default:
- return false;
- }
- }
- /**
- * Sorts array of n values using bubble sort.
- */
- void bubble(int values[], int n)
- {
- bool loop = true; //keep looping over arary while loop is true,
- //loop keep track if a change was made last iteration
- while (loop)
- {
- loop = false;
- for (int i = 0; i < n - 1; i++) //loop over array
- {
- if (values[i] > values[i + 1]) //swap values if the next one is larger
- {
- //do the swapping
- int temp = values[i];
- values[i] = values[i + 1];
- values[i + 1] = temp;
- //loop again
- loop = true;
- }
- }
- }
- }
- /**
- * Sorts array of n values using selection sort.
- */
- void selection(int values[], int n)
- {
- int sortedStart = 0; //keeps track of the sorted portion
- int min; //value of the smallest
- int minLocation; //location of the smallest
- while (sortedStart != n - 1) //loop until the sorted portion of the array is the entire array
- {
- min = 1000;
- for (int i = sortedStart; i < n; i++) // find the min value
- {
- if (values[i] < min)
- {
- min = values[i];
- minLocation = i;
- }
- }
- //move the min value, and swap
- int temp = values[sortedStart];
- values[sortedStart] = values[minLocation];
- values[minLocation] = temp;
- sortedStart++;
- }
- }
- /**
- * Sorts array of n values using insertion sort.
- */
- void insertion(int values[], int n)
- {
- int holePosition;
- int valueToInsert;
- for (int i = 1; i <= n; i++) //loop over array
- {
- //set location and value to the current place in the array being sorted
- valueToInsert = values[i];
- holePosition = i;
- //loop while the value is smaller than the one before it, while moving into the hole position
- while (holePosition > 0 && values[holePosition - 1] > valueToInsert)
- {
- values[holePosition] = values[holePosition - 1];
- holePosition--;
- }
- values[holePosition ] = valueToInsert;
- }
- }
Add Comment
Please, Sign In to add comment