12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 ©1995-2002 Barnette ND & McQuain WD 1 Sorting Many computer applications.

Slides:



Advertisements
Similar presentations
Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs.
Advertisements

Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Programming Logic & Design Second Edition by Tony Gaddis.
Sorting A fundamental operation in computer science (many programs need to sort as an intermediate step). Many sorting algorithms have been developed Choose.
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.
CS 106 Introduction to Computer Science I 02 / 29 / 2008 Instructor: Michael Eckmann.
Visual C++ Programming: Concepts and Projects
CSE 373: Data Structures and Algorithms
Simple Sorting Algorithms
Searches & Sorts V Deena Engel’s class Adapted from W. Savitch’s text An Introduction to Computers & Programming.
CS 106 Introduction to Computer Science I 02 / 28 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 07 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 03 / 2008 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 03 / 08 / 2010 Instructor: Michael Eckmann.
Algorithm Efficiency and Sorting
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Searching and Sorting Arrays
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Lecture 08 Sorting. Sorts Many programs will execute more efficiently if the data they process is sorted before processing begins. – We first looked at.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Sorting and Searching Arrays CSC 1401: Introduction to Programming with Java Week 12 – Lectures 1 & 2 Wanda M. Kunkle.
Simple Sort Algorithms Selection Sort Bubble Sort Insertion Sort.
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.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
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.
UNIT 18 Searching and Sorting.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
Examples using Arrays. Summing Squares Problem: To compute the sum of the squares of N numbers N is given N values are also given These should be read.
CSE 373 Data Structures and Algorithms
Lecture 6 Sorting Algorithms: Bubble, Selection, and Insertion.
Simple Iterative Sorting Sorting as a means to study data structures and algorithms Historical notes Swapping records Swapping pointers to records Description,
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
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.
Sorting. Algorithms Sorting reorders the elements in an array or list in either ascending or descending order. Sorting reorders the elements in an array.
Sorting – Insertion and Selection. Sorting Arranging data into ascending or descending order Influences the speed and complexity of algorithms that use.
BUBBLE SORT. Introduction Bubble sort, also known as sinking sort, is a simple sorting algorithm that works by repeatedly stepping through the list to.
ECE 103 Engineering Programming Chapter 24 Sorting Herbert G. Mayer, PSU CS Status 6/2/2015 Initial content copied verbatim from ECE 103 material developed.
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
1 2. Program Construction in Java. 2.9 Sorting 3 The need Soritng into categories is relatively easy (if, else if, switch); here we consider sorting.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
The Bubble Sort by Mr. Dave Clausen La Cañada High School.
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.
CS 162 Intro to Programming II Bubble Sort 1. Compare adjacent elements. If the first is greater than the second, swap them. Do this for each pair of.
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.
1 Principles of Computer Science I Honors Section Note Set 5 CSE 1341.
CS 106 Introduction to Computer Science I 03 / 02 / 2007 Instructor: Michael Eckmann.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Computer Science 1620 Sorting. cases exist where we would like our data to be in ascending (descending order) binary searching printing purposes selection.
Bubble Sort. Sorting  Computers only use numeric values for sorting  Does this mean you cannot sort a file by a character field (such as last name or.
CS 162 Intro to Programming II Sorting Introduction & Selection Sort 1.
Sorting & Searching Geletaw S (MSC, MCITP). Objectives At the end of this session the students should be able to: – Design and implement the following.
Basic Sorting Algorithms Dr. Yingwu Zhu. Sorting Problem Consider list x 1, x 2, x 3, … x n Goal: arrange the elements of the list in order Ascending.
The Linear and Binary Search and more Lecture Notes 9.
12. Searching/Sorting Programming in C++ Computer Science Dept Va Tech August, 2000 © Barnette ND, McQuain WD, Keenan MA 1 Simple Searching Many.
Sort Algorithm.
The Bubble Sort Mr. Dave Clausen La Cañada High School
Alternate Version of STARTING OUT WITH C++ 4th Edition
Searching and Sorting Algorithms
Introduction to Search Algorithms
Algorithm Efficiency and Sorting
Objectives At the end of the class, students are expected to be able to do the following: Understand the purpose of sorting technique as operations on.
Bubble, Selection & Insertion sort
CS 1044 Intro Programming in C++ Fall 2002
Introduction to Sorting Algorithms
Presentation transcript:

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 1 Sorting Many computer applications involve sorting the items in a list into some specified order. For example, we have seen that a list may be searched more efficiently if it is sorted. To sort a group of items, the following relationships must be clearly defined over the items to be sorted: Ascending order: smallest... largest Descending order: largest … smallest When designing or choosing an algorithm for sorting, one goal is to minimize the amount of work necessary to sort the list of items. Generally the amount of work is measured by the number of comparisons of list elements and/or the number of swaps of list elements that are performed. a<ba>ba=ba<ba>ba=b

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 2 Decision Trees To sort three items (a, b, c), how many comparisons must be made? Naively we may consider the question by drawing a diagram representing the decisions that must be made to arrive at a solution: The decision tree above assumes that the three items (a, b, c), are unique.

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 3 Bubble Sort Algorithm 1.Initialize the size of the list to be sorted to be the actual size of the list. 2.Loop through the list until no element needs to be exchanged with another to reach its correct position. 2.1Loop (i) from 0 to size of the list to be sorted Compare the i th and (i + 1) st elements in the unsorted list Swap the i th and (i + 1) st elements if not in order ( ascending or descending as desired). 2.2Decrease the size of the list to be sorted by 1. One of the simplest sorting algorithms proceeds by walking down the list, comparing adjacent elements, and swapping them if they are in the wrong order. The process is continued until the list is sorted. More formally: Each pass "bubbles" the largest element in the unsorted part of the list to its correct location. A ??

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 4 Bubble Sort Implementation void BubbleSort(int List[], int Size) { int tempInt; // temp variable for swapping list elems for (int Stop = Size - 1; Stop > 0; Stop--) { for (int Check = 0; Check < Stop; Check++) { // make a pass if (List[Check] > List[Check + 1]) { // compare elems tempInt = List[Check]; // swap if in the List[Check] = List[Check + 1]; // wrong order List[Check + 1] = tempInt; } Bubblesort compares and swaps adjacent elements; simple but not very efficient. Efficiency note: the outer loop could be modified to exit if the list is already sorted. Here is an ascending-order implementation of the bubblesort algorithm for integer arrays:

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 5 Bubble Sort Trace Trace the given implementation on the array below. Try to keep track of how many comparisons and swaps are performed. A ?? A Original array Pass 1 Pass 2 Pass 3 Pass 4 Pass 5 Pass 6 Pass 7 Pass 8 Pass 9

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 6 Selection Sort Algorithm 1. Loop (i) from 0 to the (number of elements to be sorted - 2) 1.1 Assume the smallest remaining item is at the i th position, call this location smallest. 1.2 Loop (j) through the remainder of the list to be sorted (i+1.. size-1) Compare the j th & smallest elements in the unsorted list If the j th element is < the smallest element then reset the location of the smallest to the j th location. 1.3 Move the smallest element to the head of the unsorted list, (i.e. swap the ith and smallest elements). After sorting all but 1 element the remaining element must be in its correct position. Another simple sorting algorithm proceeds by walking down the list, and finding the smallest (or largest) element, and then swapping it to the beginning of the unsorted part of the list. The process is continued until the list is sorted. More formally:

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 7 Selection Sort Implementation void SelectionSort(int List[], int Size) { int Begin, SmallSoFar, Check; void Swap(int& Elem1, int& Elem2);// see previous slide for (Begin = 0; Begin < Size - 1; Begin++) { SmallSoFar = Begin; // set head of tail for (Check = Begin + 1; Check < Size; Check++) { // scan current tail if (List[Check] < List[SmallSoFar]) SmallSoFar = Check; } Swap(List[Begin], List[SmallSoFar]); // put smallest elem at front } // of current tail } void Swap(int& Elem1, int& Elem2) { int tempInt; tempInt = Elem1; Elem1 = Elem2; Elem2 = tempInt; } Here is an ascending-order implementation of the selection sort algorithm for integer arrays:

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 8 Selection Sort Trace Trace the given implementation on the array below. Try to keep track of how many comparisons and swaps are performed. A ?? A Original array Pass 1 Pass 2 Pass 3 Pass 4 Pass 5 Pass 6 Pass 7 Pass 8 Pass 9

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 9 Sorting a List of Structured Data void sortByOrigin(Trip dB[], int numTrips) { Trip tempTrip; // temp variable for swapping list elems for (int Stop = numTrips - 1; Stop > 0; Stop--) { for (int Check = 0; Check < Stop; Check++) { // make a pass // compare Origin fields of array elements if (dB[Check].Origin > dB[Check + 1].Origin) { tempTrip = dB[Check]; // swap if in the dB[Check] = dB[Check + 1]; // wrong order dB[Check + 1] = tempTrip; } Here is an ascending-order implementation of the bubble sort algorithm for integer arrays:

12. Sorting Intro Programming in C++ Computer Science Dept Va Tech August, 2002 © Barnette ND & McQuain WD 10 Cost of Sorting Suppose the array to be sorted contains N elements. The cost of sorting may be measured by the number of array elements that must be compared to each other, or by the number of times two array elements must be swapped. Using those measures (approximately): ComparisonsSwaps WorstAverageWorstAverage Bubble SortN 2 N 2 N 2 N 2 Selection Sort N 2 N 2 N-1N-1 In some cases, comparisons are more expensive than swaps; in other cases, swaps may be more expensive than comparisons. In any case, there is no cost advantage to using Bubble Sort. There are other, more complex, sorting algorithms whose costs are on the order of Nlog 2 N — those are introduced in CS 1704.