CS 112 Introduction to Programming Sorting of an Array Debayan Gupta Computer Science Department Yale University 308A Watson, Phone: 432-6400

Slides:



Advertisements
Similar presentations
Introduction to Algorithms Quicksort
Advertisements

Garfield AP Computer Science
Lab class 10: 1. Analyze and implement the following merge-sorting program. //import java.lang.*; public class MergeSorter { /** * Sort the elements of.
Sorting Sorting is the process of arranging a list of items in a particular order The sorting process is based on specific value(s) Sorting a list of test.
CS4413 Divide-and-Conquer
Computability Start complexity. Motivation by thinking about sorting. Homework: Finish examples.
Sorting Algorithms. Motivation Example: Phone Book Searching Example: Phone Book Searching If the phone book was in random order, we would probably never.
CSC2100B Quick Sort and Merge Sort Xin 1. Quick Sort Efficient sorting algorithm Example of Divide and Conquer algorithm Two phases ◦ Partition phase.
Sorting Algorithms and Average Case Time Complexity
CMPS1371 Introduction to Computing for Engineers SORTING.
System Programming in C Lecture 4. Lecture Summary Operations with Arrays: –Searching the array –Sorting the array.
Ver. 1.0 Session 5 Data Structures and Algorithms Objectives In this session, you will learn to: Sort data by using quick sort Sort data by using merge.
CS 206 Introduction to Computer Science II 04 / 27 / 2009 Instructor: Michael Eckmann.
CS 206 Introduction to Computer Science II 12 / 09 / 2009 Instructor: Michael Eckmann.
Sorting21 Recursive sorting algorithms Oh no, not again!
1 Sorting Algorithms (Part II) Overview  Divide and Conquer Sorting Methods.  Merge Sort and its Implementation.  Brief Analysis of Merge Sort.  Quick.
CS 206 Introduction to Computer Science II 12 / 05 / 2008 Instructor: Michael Eckmann.
1 TCSS 342, Winter 2005 Lecture Notes Sorting Weiss Ch. 8, pp
CHAPTER 11 Sorting.
Sorting CS-212 Dick Steflik. Exchange Sorting Method : make n-1 passes across the data, on each pass compare adjacent items, swapping as necessary (n-1.
CS 206 Introduction to Computer Science II 12 / 08 / 2008 Instructor: Michael Eckmann.
Design and Analysis of Algorithms - Chapter 41 Divide and Conquer The most well known algorithm design strategy: 1. Divide instance of problem into two.
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.
IKI 10100I: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100I: Data.
Fall 2013 Instructor: Reza Entezari-Maleki Sharif University of Technology 1 Fundamentals of Programming Session 17 These.
Computer Science Searching & Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
CSE 373: Data Structures and Algorithms Lecture 6: Sorting 1.
Sorting CS 105 See Chapter 14 of Horstmann text. Sorting Slide 2 The Sorting problem Input: a collection S of n elements that can be ordered Output: the.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
EFFICIENCY & SORTING II CITS Scope of this lecture Quicksort and mergesort Performance comparison.
Sort Algorithms.
LAB#6. 2 Overview Before we go to our lesson we must know about : 1. data structure. 2.Algorithms. data structure is an arrangement of data in a computer.
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.
Chapter 9 Sorting. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step is.
Data Structures - CSCI 102 Selection Sort Keep the list separated into sorted and unsorted sections Start by finding the minimum & put it at the front.
M180: Data Structures & Algorithms in Java Sorting Algorithms Arab Open University 1.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
CSE 143 Lecture 16 Sorting reading: 13.1, slides created by Marty Stepp
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Sorting 9/13/2010. Introduction In CS1 you covered Insertion Sort, Bubble Sort, and Selection Sort. – In these algorithms we end up making a significant.
Sorting Algorithms Written by J.J. Shepherd. Sorting Review For each one of these sorting problems we are assuming ascending order so smallest to largest.
CS 367 Introduction to Data Structures Lecture 11.
Building Java Programs Chapter 13 Sorting reading: 13.3, 13.4.
CMPT 238 Data Structures More on Sorting: Merge Sort and Quicksort.
Searching and Sorting Searching algorithms with simple arrays
Sort Algorithm.
Prof. U V THETE Dept. of Computer Science YMA
Sorting Mr. Jacobs.
Subject Name: Design and Analysis of Algorithm Subject Code: 10CS43
slides created by Marty Stepp and Hélène Martin
SORTING AND SEARCHING.
slides adapted from Marty Stepp and Hélène Martin
Building Java Programs
CSE 154 Sorting reading: 13.3, 13.4
slides created by Marty Stepp
Yan Shi CS/SE 2630 Lecture Notes
slides created by Marty Stepp
Chapter 4.
slides created by Marty Stepp
CSE 143 Sorting reading: 13.3, 13.4.
Algorithms Dr. Youn-Hee Han April-May 2013
CSE 373 Data Structures and Algorithms
slides created by Marty Stepp and Hélène Martin
Algorithms: Design and Analysis
Sorting and Searching -- Introduction
Stacks, Queues, ListNodes
Presentation transcript:

CS 112 Introduction to Programming Sorting of an Array Debayan Gupta Computer Science Department Yale University 308A Watson, Phone:

Sorting 2

3 Roadmap: Arrays  Motivation, declaration, initialization, access  Reference semantics: arrays as objects  Example usage of arrays m Tallying: array elements as counters m Keeping state  Manipulating arrays m Sorting an array

4 Sorting an Array  The process of arranging an array of elements into some order, say increasing order, is called sorting  Many problems require sorting m Google: display from highest ranked to lower ranked m Morse code

5 Sorting in CS  Sorting is a classical topic in algorithm design

6 Sorting an Array  How do we sort an array of numbers? int[] numbers = { 3, 9, 6, 1, 2 };

Many Sorting Algorithms  Insertion sort  Selection sort  Bubble sort  Merge sort  Quick sort  … 7

8 Insertion Sort  Basic idea: divide and conquer (reduction) m reduce sorting n numbers to sort the first n-1 numbers insert the n-th number to the sorted first n-1

9 insertPos = insertPos =3 insertPos =2 insertPos =1

10 Insertion PseudoCode // assume 0 to n – 1 already sorted // now insert numbers[n] // insertPos = n; // repeat (number at insertPos-1 > to_be_inserted) { // shift larger values to the right // numbers[insertPos] <- numbers[insertPos-1]; // insertPos--; // numbers[insertPos] <- to_be_inserted;

11 // insertPos = n; // repeat (number at insertPos-1 > to_be_inserted) { // shift larger values to the right // numbers[insertPos] <- numbers[insertPos-1]; // insertPos--; // numbers[insertPos] <- to_be_inserted; 0123

12 Refinement: Insertion PseudoCode // assume 0 to n – 1 already sorted // now insert numbers[n] // insertPos = n; // repeat (insertPos > 0 && number at insertPos-1 > to_be_inserted) { // shift larger values to the right // numbers[insertPos] <- numbers[insertPos-1]; // insertPos--; // numbers[insertPos] <- to_be_inserted;

13 Insertion Sort Implementation public static void sort (int[] numbers) { for (int n = 1; n < numbers.length; index++) { int key = numbers[n]; int insertPos = n; // invariant: the elements from 0 to index -1 // are already sorted. Insert the element at // index to this sorted sublist while (insertPos > 0 && numbers[insertPos-1] > key) { // shift larger values to the right numbers[insertPos] = numbers[insertPos-1]; insertPos--; } numbers[insertPos] = key; } // end of for } // end of sort

14

15

16

17

18

19

Analysis of Insertion Sort  What is algorithm complexity in the worst case? 20 int[] numbers = { 3, 9, 6, 1, 2 };

21 Sorting Arrays: Bubble Sort  Scan the array multiple times m during each scan, if elements at i and i+1 are out of order, we swap them  This sorting approach is called bubble sort m  Remaining question: when do we stop (the termination condition)?

Sorting: Bubble Sort 22 public static void sort (int[] numbers) { boolean outOfOrder = false; do { outOfOrder = false; // one scan for (int i = 0; i < numbers.length-1; i++) { if (numbers[i] > numbers[i+1]) { // out of order // swap int x = numbers[i]; numbers[i] = numbers[i+1]; numbers[i+1] = x; outOfOrder = true; } // end of if } // end of for } while (outOfOrder); } // end of sort

23 Selection Sort  For the i-th iteration, we select the i-th smallest element and put it in its final place in the sort list

24 Selection Sort  The approach of Selection Sort: m select one value and put it in its final place in the sort list m repeat for all other values  In more detail: m find the smallest value in the list m switch it with the value in the first position m find the next smallest value in the list m switch it with the value in the second position m repeat until all values are placed

25 Selection Sort  An example: original: smallest is 1: smallest is 2: smallest is 3: smallest is 6:

26 Sorting: Selection Sort public static void sort (int[] numbers) { int min, temp; for (int i = 0; i < numbers.length-1; i++) { // identify the i-th smallest element min = i; for (int scan = i+1; scan < numbers.length; scan++) if (numbers[scan] < numbers[min]) min = scan; // swap the i-th smallest element with that at i temp = numbers[min]; numbers[min] = numbers[i]; numbers[i] = temp; } // end of for } // end of sort

Analysis of Selection Sort  What is algorithm complexity in the worst case? 27 int[] numbers = { 3, 9, 6, 1, 2 };

Roadmap  Both insertion and selection have complexity of O(N 2 )  Q: What is the best that one can do and can we achieve it? 28

Sorting: Merge Sort  Split list into two parts  Sort them separately  Combine the two sorted lists (Merge!)  Divide and Conquer! 29

Sorting 30 public void sort(int[] values) { numbers = values; // numbers has been previously declared mergesort(0, number - 1); } private void mergesort(int low, int high) { // check if low is smaller then high, if not then the array is sorted if (low < high) { // Get the index of the element which is in the middle int middle = low + (high - low) / 2; mergesort(low, middle); // Sort the left side of the array mergesort(middle + 1, high); // Sort the right side of the array merge(low, middle, high); // Combine them both }

Merging 31 private void merge(int low, int middle, int high) { // Copy both parts into the helper array for (int i = low; i <= high; i++) { helper[i] = numbers[i]; } int i = low, j = middle + 1, k = low; // Copy the smallest values from either side while (i <= middle && j <= high) { if (helper[i] <= helper[j]) { numbers[k] = helper[i]; i++; } else { numbers[k] = helper[j]; j++; } k++; } // Copy the rest of the left side of the array into the target array while (i <= middle) { numbers[k] = helper[i]; k++; i++; }

Merging

Sorting: Quick Sort  Select a random element  Compare it to every other element in your list to find out its rank or position  You have now split the list into two smaller lists (if a > x and x > b, then we know that a > b – we don’t need to compare!) 33

Quicksort 34 private void quicksort(int low, int high) { int i = low, j = high; // Get the pivot element from the middle of the list int pivot = numbers[low + (high-low)/2]; // Divide into two lists while (i <= j) { // If the current value from the left list is smaller then the pivot // element then get the next element from the left list while (numbers[i] < pivot) { i++; } // If the current value from the right list is larger then the pivot // element then get the next element from the right list while (numbers[j] > pivot) { j--; }

Quicksort.. Contd. 35 // If we have found a values in the left list which is larger then // the pivot element and if we have found a value in the right list // which is smaller then the pivot element then we exchange the // values. // As we are done we can increase i and j if (i <= j) { exchange(i, j); i++; j--; } // Recursion if (low < j) quicksort(low, j); if (i < high) quicksort(i, high); } private void exchange(int i, int j) { int temp = numbers[i]; numbers[i] = numbers[j]; numbers[j] = temp; }

What’s the best we can do?  N 2 ?  N log N  Why? 36

N log N  N! possible outcomes  If we compare two numbers, there are only 2 possible combinations that we can get  So, if we have x steps, then we can produce a total of 2 x combinations  To get 2 x > N!, we need x > N log N 37

Questions? 38