Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS150 Introduction to Computer Science 1

Similar presentations


Presentation on theme: "CS150 Introduction to Computer Science 1"— Presentation transcript:

1 CS150 Introduction to Computer Science 1
Summary Assignment 5 due today Exam 3 on Friday, November 14th, 2003 8/2/2018 CS150 Introduction to Computer Science 1

2 CS150 Introduction to Computer Science 1
Problem Write a function to return the index of the smallest element in a subarray. A subarray is a section of an array. The subarray is determined by its starting and ending indexes. The function will have the following arguments: The array, The starting index of the subarray, The ending index of the subarray, The index of the smallest element. 8/2/2018 CS150 Introduction to Computer Science 1

3 Function findIndexOfMin
void findIndexOfMin(const int x[], int startIndex, int endIndex, int& index) { index = startIndex; for(int i=startIndex + 1; i <= endIndex; i++) if(x[i] < x[index]) index = i; } 8/2/2018 CS150 Introduction to Computer Science 1

4 CS150 Introduction to Computer Science 1
Sorting Arrays Some programs run more efficiently if their data is sorted in ascending or descending order. Can you think of a way to sort an array? 8/2/2018 CS150 Introduction to Computer Science 1

5 CS150 Introduction to Computer Science 1
Selection Sort Algorithm: Starting with the fist item in the array and ending with the next to last item: Set i equal to the index of the first item in the subarray to be processed in the next steps. Find the index of the smallest item in the subarray with indexes ranging from i through n-1. Exchange the smallest item found in the previous step with item i. Write the function that performs the selection sort using the algorithm above. 8/2/2018 CS150 Introduction to Computer Science 1

6 CS150 Introduction to Computer Science 1
Selection Sort void selectionSort(int items[], int n) { int minSub; for(int i=0; i<n-1; i++) findIndexOfMin(items, i, n-1, minSub); exchange(items[minSub], items[i]); } 8/2/2018 CS150 Introduction to Computer Science 1

7 CS150 Introduction to Computer Science 1
Selection Sort void exchange(int & num1, int & num2) { int temp; temp = num1; num1 = num2; num2 = temp; } 8/2/2018 CS150 Introduction to Computer Science 1

8 CS150 Introduction to Computer Science 1
Problem Write a program to calculate the mean, median and mode of an array containing 50 numbers. The numbers in the array can only range from 0 - 9 The program should have the following functions: mean: return the average median: sort array and determine value of median element mode: most frequent response selectionSort, exchange, findIndexOfMin printArray: display the array, 10 elements per line 8/2/2018 CS150 Introduction to Computer Science 1


Download ppt "CS150 Introduction to Computer Science 1"

Similar presentations


Ads by Google