CSE 1301 J Lecture 13 Sorting Richard Gesick. CSE 1301 J 2 of 30 Sorting an Array When an array's elements are in random order, our Sequential Search.

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

VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 9A Sorting (Concepts)
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
Visual C++ Programming: Concepts and Projects
Chapter 6: Arrays Java Software Solutions for AP* Computer Science
CS0007: Introduction to Computer Programming Array Algorithms.
CPS120: Introduction to Computer Science Searching and Sorting.
An Introduction to Sorting Chapter 8 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
1 CSE1301 Computer Programming: Lecture 28 List Sorting.
Simple Sorting Algorithms
Computer Programming Sorting and Sorting Algorithms 1.
Lecture 14: A Programming Example: Sorting Yoni Fridman 7/24/01 7/24/01.
Algorithm Efficiency and Sorting
1 © 2006 Pearson Addison-Wesley. All rights reserved Searching and Sorting Linear Search Binary Search ; Reading p Selection Sort ; Reading p
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Sorting 2 An array a is sorted (ascending order) if: for all i a[i]  a[j] Probably the most well-studied algorithmic problem in Computer Science There.
Programming Logic and Design Fourth Edition, Comprehensive
1 Sorting/Searching and File I/O Sorting Searching Reading for this lecture: L&L
Value Iteration 0: step 0. Insertion Sort Array index67 Iteration i. Repeatedly swap element i with.
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.
- SEARCHING - SORTING.  Given:  The array  The search target: the array element value we are looking for  Algorithm:  Start with the initial array.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Sorting Course Lecture Slides 24 May 2010 “The real focus here is bringing.
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.
CSC 211 Data Structures Lecture 15
Section 8.4 Insertion Sort CS Insertion Sort  Another quadratic sort, insertion sort, is based on the technique used by card players to arrange.
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.
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
COMP102 Lab 131 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
Chapter 8 Single-Dimensional Arrays. Topics Declaring and Instantiating Arrays Accessing Array Elements Writing Methods Aggregate Array Operations Using.
ITEC 2620A Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: 2620a.htm Office: TEL 3049.
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.
Searching and Sorting Chapter Sorting Arrays.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
+ ARRAYS - SEARCHING - SORTING Dr. Soha S. Zaghloul updated by Rasha M. AL_Eidan 2015.
Data Structures Simple Sorts Phil Tayco Slide version 1.0 Feb. 8, 2015.
Computer Science 101 Introduction to Sorting. Sorting One of the most common activities of a computer is sorting data Arrange data into numerical or alphabetical.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
Chapter 8 Search and Sort ©Rick Mercer. Outline Understand how binary search finds elements more quickly than sequential search Sort array elements Implement.
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.
3 – SIMPLE SORTING ALGORITHMS
Sorting and Searching. Selection Sort  “Search-and-Swap” algorithm 1) Find the smallest element in the array and exchange it with a[0], the first element.
Lecture #9: Sorting Algorithms خوارزميات الترتيب Dr. Hmood Al-Dossari King Saud University Department of Computer Science 22 April 2012.
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.
ALGORITHMS.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Recursion Method calls itself iteratively until a base case is met and usually containing the following: if-else for base case with return value increment/decrement.
M180: Data Structures & Algorithms in Java Sorting Algorithms Arab Open University 1.
1 Ch. 2: Getting Started. 2 About this lecture Study a few simple algorithms for sorting – Insertion Sort – Selection Sort (Exercise) – Merge Sort Show.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
ITEC 2620M Introduction to Data Structures Instructor: Prof. Z. Yang Course Website: 20m.htm Office: TEL 3049.
Chapter 15 Running Time Analysis. Topics Orders of Magnitude and Big-Oh Notation Running Time Analysis of Algorithms –Counting Statements –Evaluating.
Chapter 9: Sorting and Searching Arrays
CS212: Data Structures and Algorithms
Introduction to Search Algorithms
Recitation 13 Searching and Sorting.
Simple Sorting Algorithms
Bubble Sort Bubble sort is one way to sort an array of numbers. Adjacent values are swapped until the array is completely sorted. This algorithm gets its.
Binary Search Back in the days when phone numbers weren’t stored in cell phones, you might have actually had to look them up in a phonebook. How did you.
ITEC 2620M Introduction to Data Structures
24 Searching and Sorting.
OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS
Simple Sorting Algorithms
Simple Sorting Algorithms
Simple Sorting Algorithms
Module 8 – Searching & Sorting Algorithms
the fourth iteration of this loop is shown here
Presentation transcript:

CSE 1301 J Lecture 13 Sorting Richard Gesick

CSE 1301 J 2 of 30 Sorting an Array When an array's elements are in random order, our Sequential Search method needs to look at every element in the array before discovering that the search key is not in the array. This is inefficient; the larger the array, the more inefficient a Sequential Search becomes. We could simplify the search by arranging the elements in numeric order, which is called sorting the array. Once the array is sorted, we can use various search algorithms to speed up a search.

CSE 1301 J 3 of 30 Selection Sort In a Selection Sort, we select the largest element in the array and place it at the end of the array. Then we select the next-largest element and put it in the next-to-last position in the array, and so on.

CSE 1301 J 4 of 30 Selection Sort To do this, we consider the unsorted portion of the array as a subarray. –We repeatedly select the largest value in the current subarray and move it to the end of the subarray, then consider a new subarray by eliminating the elements that are in their sorted locations. –We continue until the subarray has only one element. At that time, the array is sorted.

CSE 1301 J 5 of 30 The Selection Sort Algorithm To sort an array with n elements in ascending order: 1. Consider the n elements as a with m = n elements. 2. Find the index of the largest value in this subarray. 3. Swap the values of the element with the largest value and the element in the last position in the subarray. 4. Consider a new subarray of m = m - 1 elements by eliminating the last element in the previous subarray. 5. Repeat steps 2 through 4 until m = 1.

CSE 1301 J 6 of 30 Selection Sort Example In the beginning, the entire array is the unsorted subarray: We swap the largest element with the last element:

CSE 1301 J 7 of 30 Selection Sort Example (continued) Again, we swap the largest element and the last element : When there is only one unsorted element, the array is completely sorted:

CSE 1301 J 8 of 30 Swapping Values To swap two values, we define a temporary variable to hold the value of one of the elements, so that we don't lose that value during the swap. To swap elements a and b: 1. define a temporary variable, temp 2. assign element a to temp. 3. assign element b to element a. 4. assign temp to element b.

Swapping Example This code will swap elements 3 and 6 in the int array array: int temp; temp = array[3]; array[3] = array[6]; array[6] = temp; Value…33…82… Index…3…6… 33 temp Value…82… … Index…3…6… Value…82…33… Index…3…6…

CSE 1301 J 10 of 30 Selection Sort Code int temp;//temporary location for swap int max; //index of max value in subarray for ( int i = 0; i < array.length - 1; i++ ) { max = indexOfLargestElement( array, array.length - i ); // swap array[max] and // array[array.length - i - 1] temp = array[max]; array[max] = array[array.length - i - 1]; array[array.length - i - 1] = temp; }

CSE 1301 J 11 of 30 Insertion Sort The basic approach to an Insertion Sort is to sort elements much like a card player arranges the cards in sorted order in his or her hand. The player inserts cards one at a time so that the cards on the left side of the hand are sorted at all times; the cards on the right side of the hand have not been inserted into the sorted part of the hand.

CSE 1301 J 12 of 30 Insertion Sort The yellow cards are sorted and the white cards are not. To insert the 4, we compare it to the 9. 4 is smaller, so we shift 9 to the right. We compare the 4 to the 5. 4 is smaller, so we shift 5 to the right. We compare the 4 to the 3. 4 is larger, so we insert 4 into the correct slot.

CSE 1301 J 13 of 30 Insertion Sort Algorithm Insertion Sort uses a double loop. Outer Loop : executes n - 1 times and iterates through the array elements from indexes 1 through n - 1. If the variable i represents the counter of the outer loop, the array can be thought of as made of three parts:

CSE 1301 J 14 of 30 Insertion Sort Algorithm Insertion Sort uses a double loop. –a sorted subarray (although they may not be in their final position yet) from index 0 to i - 1, –the array element (at index i ) that we are currently inserting, –a subarray (from index i + 1 to n - 1) of elements that have not yet been inserted. At each iteration of the outer loop, we insert the current array element at its proper place within the sorted subarray.

CSE 1301 J 15 of 30 Insertion Sort Algorithm The inner loop compares the current array element to the elements of the sorted array from right to left and shifts these elements to the right until it finds the proper insert location. After all elements have been inserted, the array is sorted.

CSE 1301 J 16 of 30 Insertion Sort Pseudocode for i = 1 to last array index by 1 j = i temp = element at index i while ( j != 0 and value of current element is less than value of element at index j - 1 ) shift element at index j - 1 to the right decrement j by 1 assign current element value (stored in temp) to element at index j

CSE 1301 J 17 of 30 Insertion Sort Example At the beginning, the array is: The first element of the array, 17, is automatically in the correct position when we consider the subarray as consisting of that element only. The value of the outer loop counter (i) is 1, and we will now insert the second array element, 26, into the left subarray. First, we save the value of the element to be inserted by storing it in temp.

CSE 1301 J 18 of 30 Insertion Sort Example (con’t) We compare elements 26 and 17. Since 26 is larger than 17, we exit the inner loop. We then assign the value of the current element, 26, stored in temp, to the element at index j = 1; in this case, there is no change to the array. The value 26 has been inserted.

CSE 1301 J 19 of 30 Insertion Sort Example (con’t) The outer loop counter (i) is incremented, and its value is 2. We will now insert the third array element, 5, into the left subarray (at this point comprised of the two inserted elements, 17 and 26).

CSE 1301 J 20 of 30 Insertion Sort Example (con’t) The value of the inner loop counter ( j ) is set to the value of the outer loop counter (i ), i.e. 2. We compare the current element, 5, stored in temp, and 26 (index j - 1 = 1). Since 5 is smaller than 26, we shift 26 to the right and decrement j by 1; j now has the value 1.

CSE 1301 J 21 of 30 Insertion Sort Example (con’t) We then compare the current element, 5, stored in temp, and 17 (index j - 1 = 0). Since 5 is smaller than 17, we shift 17 to the right and decrement j by 1; j now has the value 0.

CSE 1301 J 22 of 30 Insertion Sort Example (con’t) Since j is 0, we exit the inner loop and assign the value of the current element, 5, stored in temp, to the array element at index j = 0. The value 5 has now been inserted.

CSE 1301 J 23 of 30 Insertion Sort Example (con’t) The outer loop counter (i) is incremented, and its value is 3. We will now insert the fourth array element, 2, into the left subarray (at this point comprised of the three inserted elements: 5, 17, and 26).

CSE 1301 J 24 of 30 Insertion Sort Example (con’t) The value of the inner loop counter ( j ) is set to the value of the outer loop counter (i ), i.e. 3. We compare the current element, 2, stored in temp, and 26 (index j - 1 = 2). Since 2 is smaller than 26, we shift 26 to the right and decrement j by 1; j now has the value 2.

CSE 1301 J 25 of 30 Insertion Sort Example (con’t) We then compare the current element, 2, stored in temp, and 17 (index j - 1 = 1). Since 2 is smaller than 17, we shift 17 to the right and decrement j by 1; j now has the value 1.

CSE 1301 J 26 of 30 Insertion Sort Example (con’t) We then compare the current element, 2, stored in temp, and 5 (index j - 1 = 0). Since 2 is smaller than 5, we shift 5 to the right and decrement j by 1; j now has the value 0.

CSE 1301 J 27 of 30 Insertion Sort Example (con’t) Since j is 0, we exit the inner loop and assign the value of the current element, 2, stored in temp, to the array element at index j. The value 2 has now been inserted. And the entire array is sorted.

CSE 1301 J 28 of 30 Insertion Sort Code int j, temp; for ( int i = 1; i < array.length; i++ ) { j = i; temp = array[i]; while ( j != 0 && array[j - 1] > temp ) { array[j] = array[j - 1]; j--; } array[j] = temp; }

CSE 1301 J 29 of 30 Sorting Arrays of Objects In arrays of objects, the array elements are object references. Thus, to sort an array of objects, we need to sort the data of the objects. Usually, one of the instance variables of the object acts as a sort key. –For example, in an object, the sort key might be the date received.

CSE 1301 J 30 of 30 Example Code to sort an array of Auto objects using model as the sort key: Auto temp; int j; for ( int i = 1; i < arr.length; i++ ) { j = i; temp = arr[i]; while ( j != 0 && ( temp.getModel( ) ).compareTo( arr[j - 1].getModel( ) ) < 0 ) { arr[j] = arr[j - 1]; j--; } // end while loop arr[j] = temp; } // end for loop