Structured programming

Similar documents
Structured programming

Lecture 6 Sorting and Searching

Programming Language B

Initialisation of an array is the process of assigning initial values. Typically declaration and initialisation are combined.

Computers in Engineering COMP 208. Where s Waldo? Linear Search. Searching and Sorting Michael A. Hawker

LECTURE 17. Array Searching and Sorting

8/2/10. Looking for something COMP 10 EXPLORING COMPUTER SCIENCE. Where is the book Modern Interiors? Lecture 7 Searching and Sorting TODAY'S OUTLINE

Chapter 17: Sorting Algorithms. 1.1 Description Performance Example: Bubble Sort Bubble Sort Algorithm 5

Computer Science Foundation Exam

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

Structured programming

Sorting is ordering a list of objects. Here are some sorting algorithms

1/ COP 3503 FALL 2012 SHAYAN JAVED LECTURE 16. Programming Fundamentals using Java

Subject: Fundamental of Computer Programming 2068

Data Structures and Algorithms for Engineers

Chapter Objectives. List Processing. Chapter 10: Applications of Arrays and Strings. Java Programming: Program Design Including Data Structures

Searching an Array: Linear and Binary Search. 21 July 2009 Programming and Data Structure 1

Sorting. Bubble Sort. Selection Sort

Programming Languages and Techniques (CIS120e)

Problem: Read 10 numbers from the keyboard and store them

Solution for Data Structure

Sorting. Bringing Order to the World

1 Short Answer (10 Points Each)

C Programming Language

Softwaretechnik. Program verification. Software Engineering Albert-Ludwigs-University Freiburg. June 30, 2011

Sorting Algorithms. Array Data is being arranged in ascending order using the bubble sort algorithm. #1 #2 #3 #4 #5 #6 #7

Computer Science & Engineering 150A Problem Solving Using Computers

Algorithms Bubble Sort (1B) Young Won Lim 4/5/18

CS Algorithms and Complexity

CS11001/CS11002 Programming and Data Structures (PDS) (Theory: 3-0-0)

Introduction to Arrays

C Language Part 2 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

CS 211: Binary Search and Sorting

Arrays (2) Applications

Sorting. Sorting. Stable Sorting. In-place Sort. Bubble Sort. Bubble Sort. Selection (Tournament) Heapsort (Smoothsort) Mergesort Quicksort Bogosort

Abstract Data Type: Stack

Chapter 10 - Notes Applications of Arrays

1 a = [ 5, 1, 6, 2, 4, 3 ] 4 f o r j i n r a n g e ( i + 1, l e n ( a ) 1) : 3 min = i

Using pointers with functions

CS 137 Part 8. Merge Sort, Quick Sort, Binary Search. November 20th, 2017

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

MTH 307/417/515 Final Exam Solutions

ECE264 Fall 2013 Exam 1, September 24, 2013

There are two possible results from a search: either you find the item you are looking for, or you don't.

UNIVERSITY OF WINDSOR Fall 2007 QUIZ # 2 Solution. Examiner : Ritu Chaturvedi Dated :November 27th, Student Name: Student Number:

Searching Elements in an Array: Linear and Binary Search. Spring Semester 2007 Programming and Data Structure 1

Arrays and Applications

CSCI 2132 Software Development Lecture 18: Implementation of Recursive Algorithms

8/5/10 TODAY'S OUTLINE. Recursion COMP 10 EXPLORING COMPUTER SCIENCE. Revisit search and sorting using recursion. Recursion WHAT DOES THIS CODE DO?

LECTURE NOTES ON DATA STRUCTURES THROUGH C

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

CS101 Computer Programming Quiz for Wednesday Batch 8 October 2014

CSE 2123 Sorting. Jeremy Morris

Sorting and Searching. Sudeshna Sarkar 7 th Feb 2017

CSCI 2132 Software Development. Lecture 19: Generating Permutations

Softwaretechnik. Program verification. Albert-Ludwigs-Universität Freiburg. June 28, Softwaretechnik June 28, / 24

COMP1511 focuses on writing programs. Effciency is also important. Often need to consider:

Indian Institute of Technology Kharagpur Programming and Data Structures (CS10001) Autumn : Mid-Semester Examination

Topic 14 Searching and Simple Sorts

CS302 - Data Structures using C++

Fundamentals of Programming & Procedural Programming

CSCI 2132 Software Development. Lecture 18: Functions

UNIVERSITY OF TORONTO FACULTY OF APPLIED SCIENCE AND ENGINEERING

CS103L SPRING 2017 UNIT 8: RECURSION

Cosc 241 Programming and Problem Solving Lecture 7 (19/3/18) Arrays

Sorting Algorithms. Selection Sort Algorithm

Elementary Sorting Algorithms

Programming Language B

Chapter Contents. An Introduction to Sorting. Selection Sort. Selection Sort. Selection Sort. Iterative Selection Sort. Chapter 9

Topics Applications Most Common Methods Serial Search Binary Search Search by Hashing (next lecture) Run-Time Analysis Average-time analysis Time anal

Programming in C Quick Start! Biostatistics 615 Lecture 4

Programming 2. Topic 8: Linked Lists, Basic Searching and Sorting

Solutions to Chapter 8

Sample Examination. Family Name:... Other Names:... Signature:... Student Number:...

Introduction To Computer Programming Laboratory Source code of a computer program is given below. What do you expect to be displayed?

What we have learned so far

! Search: find a given item in a list, return the. ! Sort: rearrange the items in a list into some. ! list could be: array, linked list, string, etc.

Bubble sort starts with very first two elements, comparing them to check which one is greater.

Two Dimensional Array - An array with a multiple indexs.

8.1. Chapter 8: Introduction to Search Algorithms. Linear Search. Linear Search. Linear Search - Example 8/23/2014. Introduction to Search Algorithms

Sorting. Popular algorithms: Many algorithms for sorting in parallel also exist.

CSCI 2132 Software Development. Lecture 20: Program Organization

Measuring algorithm efficiency

Language comparison. C has pointers. Java has references. C++ has pointers and references

Priority queues. Priority queues. Priority queue operations

C Arrays. Group of consecutive memory locations Same name and type. Array name + position number. Array elements are like normal variables

QUIZ. 0] Define arrays 1] Define records 2] How are arrays and records: (a) similar? (b) different?

(8-2) Arrays II H&K Chapter 7. Instructor - Andrew S. O Fallon CptS 121 (February 28, 2018) Washington State University

Lecture06: Pointers 4/1/2013

LECTURE 08 SEARCHING AND SORTING ARRAYS

Search,Sort,Recursion

Before we start - Announcements: There will be a LAB TONIGHT from 5:30 6:30 in CAMP 172. In compensation, no class on Friday, Jan. 31.

One Dimension Arrays 1

Arrays a kind of data structure that can store a fixedsize sequential collection of elements of the same type. An array is used to store a collection

Sorting. CPSC 259: Data Structures and Algorithms for Electrical Engineers. Hassan Khosravi

PDS Class Test 2. Room Sections No of students

ESc101: Pointers and Arrays

Data Structures And Algorithms

Lecture 11: In-Place Sorting and Loop Invariants 10:00 AM, Feb 16, 2018

Introduction. Sorting. Definitions and Terminology: Program efficiency. Sorting Algorithm Analysis. 13. Sorting. 13. Sorting.

Transcription:

Exercises 9 Version 1.0, 13 December, 2016

Table of Contents 1. Remainders from lectures.................................................... 1 1.1. What is a pointer?....................................................... 1 1.2. How to declare pointer?.................................................. 1 1.3. Why do we use pointers?................................................. 1 2. Problem 1................................................................... 1 3. Problem 2................................................................... 2 4. Problem 3................................................................... 3 4.1. Homework.............................................................. 3 4.2. Homework.............................................................. 4 5. Problem 4................................................................... 4 5.1. Bubble sort.............................................................. 5 5.2. Selection sort............................................................ 5 5.3. Insertion sort............................................................ 6 5.4. Complete Solution....................................................... 6 6. Source code of the examples and problems..................................... 8

1. Remainders from lectures 1.1. What is a pointer? Pointer is a data type that stores (points to) some memory location. This memory location is stored by its address (some number). 1.2. How to declare pointer? pointer_type *name; Example --- float *p; --- This pointer doesn t point to anything! 1.3. Why do we use pointers? For fast and efficient looping of complex data structures as arrays and trees. For efficient passing of complex arguments in functions. Passing array, struct or similar. For passing arguments whose values we want to stay affected after the function call. 2. Problem 1 Write a function that for an array of N integers will find the start and length of the largest increasing subarray. For array Example 2 3 1 4 7 12 7 9 1 1. Remainders from lectures 1

will find the array with start index 2, and length of 4 Solution p9_1_en.c #include <stdio.h> #define MAX 100 void max_increasing(int x[], int n, int *pos, int *len) { int i, start, currlen; *pos = 0; *len = 1; for (i = 0; i < n - 1; i++) { start = i; currlen = 1; while ((x[i] < x[i + 1])) { currlen++; i++; if (i == n - 1) break; if (currlen > *len) { *len = currlen; *pos = start; int main() { int a[max]; int i, n, pos, len; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &a[i]); max_increasing(a, n, &pos, &len); printf("start: %d, Length: %d\n", pos, len); return 0; 3. Problem 2 Write a program that the input array \[ a_0, a_1, a_{n-1 \] will transform into the output array: \[ b_0, b_1, b_2,, b_{n-1 \] on the following way: \[ b_0 = a_0 + a_{n-1 b_1 = a_1 + a_{n-2... b_{n-1 = a_{n-1 + a_0 \] Example Input 1 2 3 5 7 should be transformed into 8 7 6 7 8 2 3. Problem 2

Solution p9_2_en.c #include <stdio.h> #define MAX 100 void transform(int *a, int n) { int i, j; for (i = 0, j = n - 1; i < j; i++, j--) { *(a + i) += *(a + j); *(a + j) = *(a + i); if (n % 2) { *(a + n / 2) *= 2; int main() { int i, n; int a[max]; scanf("%d", &n); for (i = 0; i < n; i++) scanf("%d", &a[i]); for (i = 0; i < n; i++) printf("a[i] = %d\n", a[i]); transform(a, n); for (i = 0; i < n; i++) printf("b[i] = %d\n", a[i]); return 0; 4. Problem 3 Write the following functions for searching an array: Linear search Binary search Then write a program that fill an array with numbers from 1 to 1000000, and than generates random number in this range and finds its index by calling the two functions for searching. 4.1. Homework For the functions count and compare the number of needed iterations to find the number. 4. Problem 3 3

Solution p9_3_en.c #include <stdio.h> #include <stdlib.h> #include <time.h> #define MAX 1000000 int linear_search(int *a, int n, int key) { for (i = 0; i < n; i++) { if (*(a + i) == key) return i; return -1; int binary_search(int *a, int n, int key) { int start = 0; int end = n - 1; while (start <= end) { int mid = (start + end) / 2; if (*(a + mid) == key) return mid; else if (*(a + mid) > key) end = mid - 1; else start = mid + 1; return -1; int main() { int *a = malloc(sizeof(int) * MAX); for (i = 0; i < MAX; i++) { *(a + i) = i + 1; srand(time(null)); int key = rand() % MAX + 1; printf("element for search: %d\n", key); int found = linear_search(a, MAX, key); printf("found with linear search at position: %d\n", found); found = binary_search(a, MAX, key); printf("found with binary search at position: %d\n", found); return 0; 4.2. Homework Write a recursive function for binary search. 5. Problem 4 Write functions for sorting array by using the following methods for sorting: Bubble sort Selection sort Insertion sort Write functions fro reading and printing elements of an array, and write main program to test the sort functions. 4 4.2. Homework

5.1. Bubble sort Solution p9_4_en.c void bubble_sort(int *a, int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < n - i - 1; j++) { if (a[j] > a[j + 1]) swap(&a[j], &a[j + 1]); The method starts with comparing the first element with its neighbour until we reach the last element. In each comparison, if the previous has larger value, then they swap their values. That way the largest element is moved to the last position in the array. This method is repeated from 1-st to the last but one element in the array, so this position will float the element that is largest but smaller than the last element in the array. At the and we compare only the 1-st and 2-nd element of the array. 5.2. Selection sort Solution p9_4_en.c void selection_sort(int a[], int n, int m) { if (n - m == 1) return; else { int smallest = a[m]; int smallest_index = m; for (i = m; i < n; ++i) if (a[i] < smallest) { smallest = a[i]; smallest_index = i; swap(&a[m], &a[smallest_index]); selection_sort(a, n, m + 1); We find the smallest element of the array and we swap the value of this element with the first element. After that, the first element is ignored (since its smallest) and recursively the method is repeated to rest of the array (second element, until the end). The recursion stops when there is only one element left. That is the final step, and the sorting is done. 5.1. Bubble sort 5

5.3. Insertion sort Solution p9_4_en.c void insertion_sort(int a[], int n) { int i, j; for (i = 1; i < n; i++) { int temp = a[i]; j = i - 1; while (temp < a[j] && j >= 0) { a[j + 1] = a[j]; j--; a[j + 1] = temp; With this method we sort by inserting each element in appropriate position, hence the name of the sort. After the first iteration, the second element a[1] is compared to the first element a[0]. After the second iteration the third element is compared with first and the second. In general, in each iteration the element is compared with all elements in front of it. If the comparison shows that the element should be inserted at some position, then we make space by shifting all elements one place in right. This procedure is repeated for each element in the array. 5.4. Complete Solution 6 5.3. Insertion sort

Solution p9_4_en.c #include <stdio.h> void bubble_sort(int *a, int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < n - i - 1; j++) { if (a[j] > a[j + 1]) swap(&a[j], &a[j + 1]); void selection_sort(int a[], int n, int m) { if (n - m == 1) return; else { int smallest = a[m]; int smallest_index = m; for (i = m; i < n; ++i) if (a[i] < smallest) { smallest = a[i]; smallest_index = i; swap(&a[m], &a[smallest_index]); selection_sort(a, n, m + 1); void insertion_sort(int a[], int n) { int i, j; for (i = 1; i < n; i++) { int temp = a[i]; j = i - 1; while (temp < a[j] && j >= 0) { a[j + 1] = a[j]; j--; a[j + 1] = temp; void insert(int a[], int n) { for(i = 0; i < n; i++) { printf("a[%d] = ", i); scanf("%d", &a[i]); void print(int *a, int n) { for(i = 0; i < n; i++) { printf("%d\t", *(a + i)); printf("\n"); int main() { int a[max], n; scanf("%d", &n); insert(a, n); bubble_sort(a, n); //selection_sort(a, n, 0); //insertion_sort(a, n); print(a, n); return 0; 5.3. Insertion sort 7

6. Source code of the examples and problems https://github.com/finki-mk/sp/ Source code ZIP 8 6. Source code of the examples and problems