Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)

Slides:



Advertisements
Similar presentations
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Advertisements

 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
Insertion sort, Merge sort COMP171 Fall Sorting I / Slide 2 Insertion sort 1) Initially p = 1 2) Let the first p elements be sorted. 3) Insert the.
Recursion Chapter 11 Chapter 11.
Simple Sorting Algorithms
Searching and Sorting SLA Computer Science 4/16/08 Allison Mishkin.
Cmpt-225 Sorting. Fundamental problem in computing science  putting a collection of items in order Often used as part of another algorithm  e.g. sort.
Algorithm Efficiency and Sorting
J. Michael Moore Searching & Sorting CSCE 110. J. Michael Moore Searching with Linear Search Many times, it is necessary to search an array to find a.
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
1 Two-Dimensional Arrays. 2 Can be visualized as consisting m rows, each of n columns Syntax: datatype arrayname [row] [ column] ; Example: int val[3]
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
Simple Sorting Algorithms. 2 Bubble sort Compare each element (except the last one) with its neighbor to the right If they are out of order, swap them.
Simple Sorting Algorithms. 2 Outline We are going to look at three simple sorting techniques: Bubble Sort, Selection Sort, and Insertion Sort We are going.
Week 11 Sorting Algorithms. Sorting Sorting Algorithms A sorting algorithm is an algorithm that puts elements of a list in a certain order. We need sorting.
1 Data Structures and Algorithms Sorting. 2  Sorting is the process of arranging a list of items into a particular order  There must be some value on.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
UNIT 18 Searching and Sorting.
Lecture 5 Searching and Sorting Richard Gesick. The focus Searching - examining the contents of the array to see if an element exists within the array.
Chapter 14 Searching and Sorting Section 1 - Sequential or Linear Search Section 2 - Binary Search Section 3 - Selection Sort Section 4 - Insertion Sort.
© 2004 Pearson Addison-Wesley. All rights reserved October 17, 2007 Searching (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Searching. The process used to find the location of a target among a list of objects Searching an array finds the index of first element in an array containing.
CSE 373 Data Structures and Algorithms
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Merge sort, Insertion sort. Sorting I / Slide 2 Sorting * Selection sort (iterative, recursive?) * Bubble sort.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
© 2004 Pearson Addison-Wesley. All rights reserved October 19, 2007 Sorting ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
Sort Algorithms.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 3.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Review 1 Selection Sort Selection Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Lecture No. 04,05 Sorting.  A process that organizes a collection of data into either ascending or descending order.  Can be used as a first step for.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
© 2004 Pearson Addison-Wesley. All rights reserved March 10, 2006 Sorting ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)
CS 367 Introduction to Data Structures Lecture 11.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
1 Chapter 2 Algorithm Analysis All sections. 2 Complexity Analysis Measures efficiency (time and memory) of algorithms and programs –Can be used for the.
Dr. Sajib Datta CSE 1320 Arrays, Search and Sort.
Array Sort. Sort Pass 1 Sort Pass 2 Sort Pass 3.
Sorting Algorithms. Sorting Sorting is a process that organizes a collection of data into either ascending or descending order. public interface ISort.
Chapter 9: Sorting and Searching Arrays
CS212: Data Structures and Algorithms
Sorting Mr. Jacobs.
Growth of Functions & Algorithms
CprE 185: Intro to Problem Solving (using C)
Lecture 14 Searching and Sorting Richard Gesick.
Recitation 13 Searching and Sorting.
Simple Sorting Algorithms
CprE 185: Intro to Problem Solving (using C)
Sorting October 20, 2006 ComS 207: Programming I (in Java)
CSC215 Lecture Algorithms.
CprE 185: Intro to Problem Solving (using C)
Lecture 11 Searching and Sorting Richard Gesick.
Sorting.
Searching and Sorting 1-D Arrays
Sorting.
Simple Sorting Algorithms
UNIT – IV Searching – Linear search - binary search Sorting
Simple Sorting Algorithms
Module 8 – Searching & Sorting Algorithms
Presentation transcript:

Instructor: Alexander Stoytchev CprE 185: Intro to Problem Solving (using C)

Administrative Stuff HW6 is today (Oct 8pm. HW7 is due this Friday (Oct 8pm.

Administrative Stuff Midterm 2 is next week  Same format as before:  Lab exam during your regular lab time (Oct 27 or Oct 28)  Lecture exam on Oct 28 The exam will be cumulative with emphasis on conditional statements (if, if-else, switch), loops (do, while, for), arrays (to be covered), and searching and sorting algorithms (to be covered).

Linear Search in a Sorted Array

Problem: Find the index of a number in a sorted array of integers LinearSearch_InSortedArray.c

LinearSearch_InSortedArray.c #include #define N 12 int main() { int a[N]= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91}; int target = 62;//int target = 72;// Try this target next int i, idx=-1; for(i=0; i< N; i++) { if(a[i] == target) { idx=i; break; } else if(a[i]>target) break; // we can stop here } if(idx == -1) printf("Target not found.\n\n"); else printf("Target found at index: %d. \n\n", idx); }

Analysis If the list is unsorted we have to search all numbers before we declare that the target is not present in the array. Because the list is sorted we can stop as soon as we reach a number that is greater than our target Can we do even better?

Binary Search At each step it splits the remaining array elements into two groups Therefore, it is faster than the linear search Works only on an already SORTED array Thus, there is a performance penalty for sorting the array [

Example: Successful Binary Search

Example: BinarySearch.c

Binary_Search.c #include #define N 12 int main() { int a[N]= { 4, 7, 8, 10, 14, 21, 22, 36, 62, 77, 81, 91}; //sorted in increasing order int i; int target = 22;//int target = 72; // Try this target next int idx=-1; // if the target is found its index is stored here int first=0; // initial values for the three search varaibles int last= N-1; int mid= (first + last)/2; while(last >= first) { if( a[mid] == target) { idx=mid; // Found it! break; // exit the while loop } else if(a[mid] > target) { // don't search in a[mid]... a[last] last = mid-1; } else { // don't search in a[first]... a[mid] first = mid +1; } // recalculate mid for the next iteration mid = (first + last)/2; // integer division! } // end of while loop if(idx == -1) printf("Target not found.\n\n"); else printf("Target found at index: %d \n\n", idx); }

Analysis of Searching Methods For an array of size n Sequential Search (Average-Case) n/2 Sequential Search (Worst-Case) n Binary Search (Average-Case) log(n)/2 Binary Search (Worst-Case) log(n)

Other Stuff in Chapter 8

Two-Dimensional Arrays int Matrix[2][3]; Defines the following elements:  Row1: Matrix[0][0], Matrix[0][1], Matrix[0][2]  Row2: Matrix[1][0], Matrix[1][1], Matrix[1][2]

Two-Dimensional Arrays int Matrix[2][3]; Initialization: Matrix[0][0]=3; Matrix[0][1]=4; Matrix[0][2]=5; Matrix[1][0]=1; Matrix[1][1]= -20; Matrix[1][2]=7;

Two-Dimensional Arrays Initialization when defined: int Matrix[2][3] = { {3, 4, 5}, {1, -20, 7}};

Two-Dimensional Arrays 2D arrays and nested for loop int Matrix[2][3] = { {3, 4, 5}, {1, -20, 7}}; int i,j; for(i=0; i< 2; i++) { for(j=0; j<3; j++) printf(“%3d ”, Matrix[i][j]); printf(“\n”); }

Sorting Algorithms CprE 185: Intro to Problem Solving Iowa State University, Ames, IA Copyright © Alexander Stoytchev

Chapter 8 (Sorting)

Insertion Sort [ 0

Analogy: Sorting Cards

First Iteration First Iteration (All face up cards are sorted. End of the first iteration.)

Second Iteration Second Iteration (All face up cards are sorted. End of the second iteration.)

Third Iteration Third Iteration (All face up cards are sorted. End of the third iteration.)

Fourth Iteration Fourth Iteration (All face up cards are sorted. End of the fourth iteration.)

Fifth Iteration Fifth Iteration (All face up cards are sorted. End of the fifth iteration.)

Swapping Array Elements [

First Iteration (array-like swapping) First Iteration (All face up cards are sorted. End of the first iteration.)

Second Iteration (array-like swapping) Second Iteration (All face up cards are sorted. End of the second iteration.)

[ Example: Insertion Sort

Animations for Insertion Sort [

Animations of Sorting Algoritms

C code // Swap a[i] with the smallest element int temp = a[i]; a[i] = a[minIndex]; a[minIndex] = temp;

Example: InsertionSort.c

// Insertion Sort #include #define N 6 int main() { int a[N]= { 23, 78, 45, 8, 32, 56}; int i; for(i = 1; i < N; i++) { int j = i; int INS = a[i]; while ((j > 0) && (a[j-1] > INS)) { a[j] = a[j-1]; // shift elements to the right j--; } a[j] = INS; // insert the element } system("pause"); }

Selection Sort (Cards Example)

Initial Configuration (search all cards and find the largest)

Swap the two cards

As before, the swap is performed in three steps.

SortedUnsorted Among the remaining cards the king is the largest. It will remain in place. But the algorithm may perform Some empty operations (ie., swap it with itself in place)

SortedUnsorted Among the remaining cards the queen is the largest. It will remain in place. But the algorithm may perform Some empty operations (i.e., swap it with itself in place)

SortedUnsorted Among the remaining cards the Jack is the largest. It will remain in place. But the algorithm may perform Some empty operations (i.e., swap it with itself in place)

As before, the swap is performed in three steps.

SortedUnsorted We are down to the last card. Because there is only one and Because we know that it is Smaller than all the rest We don’t need to do anything Else with it. This is why the Algorithm goes up to < N-1

Sorted All cards are now sorted.

Selection Sort [

Example: Selection Sort [

Example: SelectionSort.c

// Selection Sort #include #define N 6 int main() { int a[N]= { 23, 78, 45, 8, 32, 56}; int i,j; // Sort the array using Selection Sort int minIndex; for(i=0; i < N-1; i++) { // find the minimum element in the unsorted part of the array minIndex=i; for(j=i+1; j < N; j++) if(a[j] < a[minIndex]) minIndex = j; // Swap a[i] with the smallest element int temp = a[i]; a[i] = a[minIndex]; a[minIndex] = temp; } system("pause"); }

Bubble Sort (Cards Example)

Initial Configuration Unsorted

First iteration of the outer loop

End of the first iteration (the smallest card is placed last) SortedUnsortedSortedUnsorted

End of the 2nd iteration (the smallest two cards are placed last) 2nd Iteration SortedUnsorted

End of the 3rd iteration (the smallest three cards are placed last) 3rd Iteration SortedUnsorted

End of the 4-th iteration all cards are sorted 4-th Iteration SortedUnsorted Sorted The last card (the Ace) Is automatically sorted. We don’t need to do anything extra.

Bubble Sort [ 0

Example: Bubble Sort

Example: BubbleSort.c

// Bubble Sort #include #define N 6 int main() { int a[N]= { 23, 78, 45, 8, 32, 56}; int i, j; // Sort the array using Bubble Sort // Last elements in the array are sorted first (in decreasing order) for(i=0; i < N; i++) { for(j=0; j< N-1-i; j++) if (a[j+1] > a[j]) /* compare the two neighbors */ { int tmp = a[j]; /* swap a[j] and a[j+1] */ a[j] = a[j+1]; a[j+1] = tmp; }

Analysis: all three run in O(n 2 ) time [

Analysis There are faster sorting algorithms  Heap sort  Quick sort  Merge Sort We will not cover those but feel free to study them on your own. They run in O(n log n) time.

O(n log n) sorting algorithms [

Questions?

THE END