mDot program that generates random numbers and sorts them, outputting to USB debug.

Dependencies:   mbed

Fork of mDot_helloworld by MultiTech

Committer:
kellybs1
Date:
Sat Aug 05 13:06:18 2017 +0000
Revision:
2:3c65515d63e3
Parent:
1:34c1fcb8ea5a
Playing around with mDot

Who changed what in which revision?

UserRevisionLine numberNew contents of line
mfiore 0:fdc94d24e54a 1 /*************************************
kellybs1 2:3c65515d63e3 2 * This simple example program
kellybs1 2:3c65515d63e3 3 * randomly generates a small array
kellybs1 2:3c65515d63e3 4 * of integers and then sorts them,
kellybs1 2:3c65515d63e3 5 * displaying at the end of each
kellybs1 2:3c65515d63e3 6 * sort step
mfiore 0:fdc94d24e54a 7 ************************************/
mfiore 0:fdc94d24e54a 8
mfiore 0:fdc94d24e54a 9 #include "mbed.h"
mfiore 0:fdc94d24e54a 10
kellybs1 2:3c65515d63e3 11 void swap(int nums [], int indexA, int indexB)
kellybs1 2:3c65515d63e3 12 {
kellybs1 2:3c65515d63e3 13 //throw value in a temp value
kellybs1 2:3c65515d63e3 14 int temp = nums[indexA];
kellybs1 2:3c65515d63e3 15 //move second into first
kellybs1 2:3c65515d63e3 16 nums[indexA] = nums[indexB];
kellybs1 2:3c65515d63e3 17 //move temp into second
kellybs1 2:3c65515d63e3 18 nums[indexB] = temp;
mfiore 0:fdc94d24e54a 19 }
mfiore 0:fdc94d24e54a 20
kellybs1 2:3c65515d63e3 21 int main()
kellybs1 2:3c65515d63e3 22 {
kellybs1 2:3c65515d63e3 23 int loopEnd = 8;
kellybs1 2:3c65515d63e3 24 int nums [loopEnd];
mfiore 0:fdc94d24e54a 25
mfiore 0:fdc94d24e54a 26 while (true) {
kellybs1 2:3c65515d63e3 27 printf("\nHello world! I am an mDot sorting random numbers\n");
kellybs1 2:3c65515d63e3 28 //fill array with pseudorandom numbers
kellybs1 2:3c65515d63e3 29 for (int i = 0; i < loopEnd; i++)
kellybs1 2:3c65515d63e3 30 nums[i] = rand() % 100;
kellybs1 2:3c65515d63e3 31
kellybs1 2:3c65515d63e3 32 //Bubble sort!
kellybs1 2:3c65515d63e3 33 for (int i = 0; i < loopEnd; i++) //check every value
kellybs1 2:3c65515d63e3 34 {
kellybs1 2:3c65515d63e3 35 for (int j = i; j < loopEnd; j++) //against every value after it
kellybs1 2:3c65515d63e3 36 {
kellybs1 2:3c65515d63e3 37 if (nums[i] > nums[j] && i != j) //swap if unsorted and not the same element
kellybs1 2:3c65515d63e3 38 {
kellybs1 2:3c65515d63e3 39 swap(nums, i, j);
kellybs1 2:3c65515d63e3 40 }
kellybs1 2:3c65515d63e3 41 }
kellybs1 2:3c65515d63e3 42 //output this step
kellybs1 2:3c65515d63e3 43 for(int i = 0; i < loopEnd; i++)
kellybs1 2:3c65515d63e3 44 printf( "%d ", nums[i]);
kellybs1 2:3c65515d63e3 45 printf("\n");
kellybs1 2:3c65515d63e3 46 wait(1);
kellybs1 2:3c65515d63e3 47 }
kellybs1 2:3c65515d63e3 48 wait(3);
mfiore 0:fdc94d24e54a 49 }
mfiore 0:fdc94d24e54a 50 }