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.

Slides:



Advertisements
Similar presentations
P p Two slow but simple algorithms are Selectionsort and Insertionsort. p p This presentation demonstrates how the two algorithms work. Quadratic Sorting.
Advertisements

CSE Lecture 3 – Algorithms I
Sorting I Chapter 8 Kruse and Ryba. Introduction Common problem: sort a list of values, starting from lowest to highest. –List of exam scores –Words of.
  Chapter 12 presents several common algorithms for sorting an array of integers.   Two slow but simple algorithms are Selectionsort and Insertionsort.
Sorting A fundamental operation in computer science (many programs need to sort as an intermediate step). Many sorting algorithms have been developed Choose.
 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
Sorting Algorithms and Average Case Time Complexity
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Sorting Part 2 CS221 – 3/4/09. Announcements Midterm: 3/11 – 15% of your total grade – We will review in class on 3/9 – You can bring one sheet of paper.
Sorting1 Sorting Order in the court!. sorting2 Importance of sorting Sorting a list of values is a fundamental task of computers - this task is one of.
CSC212 Data Structure - Section FG Lecture 21 Quadratic Sorting Instructor: Zhigang Zhu Department of Computer Science City College of New York.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
Copyright © 1999, Carnegie Mellon. All Rights Reserved. Chapter 12 presents several common algorithms for sorting an array of integers. Two slow but simple.
C++ Plus Data Structures
CS 104 Introduction to Computer Science and Graphics Problems Data Structure & Algorithms (3) Recurrence Relation 11/11 ~ 11/14/2008 Yang Song.
1 Foundations of Software Design Fall 2002 Marti Hearst Lecture 20: Sorting.
Algorithm Efficiency and Sorting
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 11 Sorting and Searching.
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.
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.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
CSC 211 Data Structures Lecture 15
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.
CHAPTER 09 Compiled by: Dr. Mohammad Omar Alhawarat Sorting & Searching.
Sorting. Introduction Common problem: sort a list of values, starting from lowest to highest. List of exam scores Words of dictionary in alphabetical.
 Pearson Education, Inc. All rights reserved Searching and Sorting.
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 19: Searching and Sorting.
 2006 Pearson Education, Inc. All rights reserved Searching and Sorting.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
Sorting Sorting Arranging items in a collection so that there is an ordering on one (or more) of the fields in the items Sort Key The field (or fields)
© M. Gross, ETH Zürich, 2014 Informatik I für D-MAVT (FS 2014) Exercise 12 – Data Structures – Trees Sorting Algorithms.
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.
Sorting Chapter Sorting Consider list x 1, x 2, x 3, … x n We seek to arrange the elements of the list in order –Ascending or descending Some O(n.
Fundamentals of Algorithms MCS - 2 Lecture # 15. Bubble Sort.
CSC211 Data Structures Lecture 21 Quadratic Sorting Instructor: Prof. Xiaoyan Li Department of Computer Science Mount Holyoke College.
Sort Algorithms.
1 C++ Plus Data Structures Nell Dale Chapter 10 Sorting and Searching Algorithms Slides by Sylvia Sorkin, Community College of Baltimore County - Essex.
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.
3 – SIMPLE SORTING ALGORITHMS
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.
Sorting and Searching by Dr P.Padmanabham Professor (CSE)&Director
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Chapter 9 Sorting 1. The efficiency of data handling can often be increased if the data are sorted according to some criteria of order. The first step.
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.
Searching and Sorting Searching: Sequential, Binary Sorting: Selection, Insertion, Shell.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
PREVIOUS SORTING ALGORITHMS  BUBBLE SORT –Time Complexity: O(n 2 ) For each item, make (n –1) comparisons Gives: Comparisons = (n –1) + (n – 2)
Review 1 Merge Sort Merge Sort Algorithm Time Complexity Best case Average case Worst case Examples.
Chapter 9: Sorting1 Sorting & Searching Ch. # 9. Chapter 9: Sorting2 Chapter Outline  What is sorting and complexity of sorting  Different types of.
Chapter 16: Searching, Sorting, and the vector Type.
INTRO2CS Tirgul 8 1. Searching and Sorting  Tips for debugging  Binary search  Sorting algorithms:  Bogo sort  Bubble sort  Quick sort and maybe.
UNIT - IV SORTING By B.Venkateswarlu Dept of CSE.
Lecture 14 Searching and Sorting Richard Gesick.
Sorting Chapter 13 presents several common algorithms for sorting an array of integers. Two slow but simple algorithms are Selectionsort and Insertionsort.
Design and Analysis of Algorithms
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.
Sorting.
Quadratic Sorting Chapter 12 presents several common algorithms for sorting an array of integers. Two slow but simple algorithms are Selectionsort and.
Lecture 11 Searching and Sorting Richard Gesick.
MSIS 655 Advanced Business Applications Programming
Sorting "There's nothing in your head the sorting hat can't see. So try me on and I will tell you where you ought to be." -The Sorting Hat, Harry Potter.
Sorting Chapter 13 presents several common algorithms for sorting an array of integers. Two slow but simple algorithms are Selectionsort and Insertionsort.
Sorting.
Presentation transcript:

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 algorithm in lots of areas: Science Engineering Business ……

Quadratic Sorting Algorithms We are given n records to sort. There are a number of simple sorting algorithms whose worst and average case performance is quadratic O(n 2 ): –Selection sort –Insertion sort –Bubble sort

Sorting an Array of Integers Example: we are given an array of six integers that we want to sort from smallest to largest [0] [1] [2] [3] [4] [5]

Selection sort

The Selection Sort Algorithm Start by finding the smallest entry. [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm Swap the smallest entry with the first entry. [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm Swap the smallest entry with the first entry. [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm Part of the array is now sorted. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm Find the smallest element in the unsorted side. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm Swap with the front of the unsorted side. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm We have increased the size of the sorted side by one element. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm The process continues... Sorted side Unsorted side Smallest from unsorted Smallest from unsorted [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm The process continues... Sorted side Unsorted side [0] [1] [2] [3] [4] [5] Swap with front Swap with front

The Selection Sort Algorithm The process continues... Sorted side Unsorted side Sorted side is bigger Sorted side is bigger [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm The process keeps adding one more number to the sorted side. The sorted side has the smallest numbers, arranged from small to large. Sorted side Unsorted side [0] [1] [2] [3] [4] [5]

The Selection Sort Algorithm We can stop when the unsorted side has just one number, since that number must be the largest number. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Selection Sort Algorithm The array is now sorted. We repeatedly selected the smallest element, and moved this element to the front of the unsorted side. [0] [1] [2] [3] [4] [5]

Selection sort animation

template void selection_sort(Item data[ ], size_t n) { size_t i, j, smallest; Item temp; if(n < 2) return; // nothing to sort!! for(i = 0; i < n-1 ; ++i) { // find smallest in unsorted part of array smallest = i; for(j = i+1; j < n; ++j) if(data[smallest] > data[j]) smallest = j; // put it at front of unsorted part of array (swap) temp = data[i]; data[i] = data[smallest]; data[smallest] = temp; }

Selection Time Sort Analysis In O-notation, what is: –Worst case running time for n items? –Average case running time for n items? Steps of algorithm: for i = 1 to n-1 find smallest key in unsorted part of array swap smallest item to front of unsorted array decrease size of unsorted array by 1

Selection Time Sort Analysis In O-notation, what is: –Worst case running time for n items? –Average case running time for n items? Steps of algorithm: for i = 1 to n-1 O(n) find smallest key in unsorted part of array O(n) swap smallest item to front of unsorted array decrease size of unsorted array by 1 Selection sort analysis: O(n 2 )

template void selection_sort(Item data[ ], size_t n) { size_t i, j, smallest; Item temp; if(n < 2) return; // nothing to sort!! for(i = 0; i < n-1 ; ++i) { // find smallest in unsorted part of array smallest = i; for(j = i+1; j < n; ++j) if(data[smallest] > data[j]) smallest = j; // put it at front of unsorted part of array (swap) temp = data[i]; data[i] = data[smallest]; data[smallest] = temp; } Outer loop: O(n)

template void selection_sort(Item data[ ], size_t n) { size_t i, j, smallest; Item temp; if(n < 2) return; // nothing to sort!! for(i = 0; i < n-1 ; ++i) { // find smallest in unsorted part of array smallest = i; for(j = i+1; j < n; ++j) if(data[smallest] > data[j]) smallest = j; // put it at front of unsorted part of array (swap) temp = data[i]; data[i] = data[smallest]; data[smallest] = temp; } Outer loop: O(n) Inner loop: O(n)

Insertion sort

The Insertion Sort Algorithm The Insertion Sort algorithm also views the array as having a sorted side and an unsorted side. [0] [1] [2] [3] [4] [5]

The Insertion Sort Algorithm The sorted side starts with just the first element, which is not necessarily the smallest element. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertion Sort Algorithm The sorted side grows by taking the front element from the unsorted side... [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertion Sort Algorithm...and inserting it in the place that keeps the sorted side arranged from small to large. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertion Sort Algorithm [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertion Sort Algorithm Sometimes we are lucky and the new inserted item doesn't need to move at all. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

The Insertionsort Algorithm Sometimes we are lucky twice in a row. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

How to Insert One Element ¶Copy the new element to a separate location. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

How to Insert One Element ·Shift elements in the sorted side, creating an open space for the new element. [0] [1] [2] [3] [4] [5]

How to Insert One Element ·Shift elements in the sorted side, creating an open space for the new element. [0] [1] [2] [3] [4] [5]

How to Insert One Element ·Continue shifting elements... [0] [1] [2] [3] [4] [5]

How to Insert One Element ·Continue shifting elements... [0] [1] [2] [3] [4] [5]

How to Insert One Element ·...until you reach the location for the new element. [0] [1] [2] [3] [4] [5]

How to Insert One Element ¸Copy the new element back into the array, at the correct location. [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

How to Insert One Element The last element must also be inserted. Start by copying it... [0] [1] [2] [3] [4] [5] Sorted side Unsorted side

Sorted Result [0] [1] [2] [3] [4] [5]

Insertion Sort animation

template void insertion_sort(Item data[ ], size_t n) { size_t i, j; Item temp; if(n < 2) return; // nothing to sort!! for(i = 1; i < n; ++i) { // take next item at front of unsorted part of array // and insert it in appropriate location in sorted part of array temp = data[i]; for(j = i; data[j-1] > temp and j > 0; --j) data[j] = data[j-1]; // shift element forward data[j] = temp; }

Insertion Sort Time Analysis In O-notation, what is: –Worst case running time for n items? –Average case running time for n items? Steps of algorithm: for i = 1 to n-1 take next key from unsorted part of array insert in appropriate location in sorted part of array: for j = i down to 0, shift sorted elements to the right if key > key[i] increase size of sorted array by 1

Insertion Sort Time Analysis In O-notation, what is: –Worst case running time for n items? –Average case running time for n items? Steps of algorithm: for i = 1 to n-1 take next key from unsorted part of array insert in appropriate location in sorted part of array: for j = i down to 0, shift sorted elements to the right if key > key[i] increase size of sorted array by 1 Outer loop: O(n)

Insertion Sort Time Analysis In O-notation, what is: –Worst case running time for n items? –Average case running time for n items? Steps of algorithm: for i = 1 to n-1 take next key from unsorted part of array insert in appropriate location in sorted part of array: for j = i down to 0, shift sorted elements to the right if key > key[i] increase size of sorted array by 1 Outer loop: O(n) Inner loop: O(n)

template void insertion_sort(Item data[ ], size_t n) { size_t i, j; Item temp; if(n < 2) return; // nothing to sort!! for(i = 1; i < n; ++i) { // take next item at front of unsorted part of array // and insert it in appropriate location in sorted part of array temp = data[i]; for(j = i; data[j-1] > temp and j > 0; --j) data[j] = data[j-1]; // shift element forward data[j] = temp; } O(n)

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5]

Bubble sort

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] Swap?

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] Yes!

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] Swap?

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] No.

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] Swap?

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] No.

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] Swap?

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] Yes!

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] Swap?

The Bubble Sort Algorithm The Bubble Sort algorithm looks at pairs of entries in the array, and swaps their order if needed. [0] [1] [2] [3] [4] [5] Yes!

The Bubble Sort Algorithm Repeat. [0] [1] [2] [3] [4] [5] Swap? No.

The Bubble Sort Algorithm Repeat. [0] [1] [2] [3] [4] [5] Swap? No.

The Bubble Sort Algorithm Repeat. [0] [1] [2] [3] [4] [5] Swap? Yes.

The Bubble Sort Algorithm Repeat. [0] [1] [2] [3] [4] [5] Swap? Yes.

The Bubble Sort Algorithm Repeat. [0] [1] [2] [3] [4] [5] Swap? Yes.

The Bubble Sort Algorithm Repeat. [0] [1] [2] [3] [4] [5] Swap? Yes.

The Bubble Sort Algorithm Repeat. [0] [1] [2] [3] [4] [5] Swap? No.

The Bubble Sort Algorithm Loop over array n-1 times, swapping pairs of entries as needed. [0] [1] [2] [3] [4] [5] Swap? No.

The Bubble Sort Algorithm Loop over array n-1 times, swapping pairs of entries as needed. [0] [1] [2] [3] [4] [5] Swap? Yes.

The Bubble Sort Algorithm Loop over array n-1 times, swapping pairs of entries as needed. [0] [1] [2] [3] [4] [5] Swap? Yes.

The Bubble Sort Algorithm Loop over array n-1 times, swapping pairs of entries as needed. [0] [1] [2] [3] [4] [5] Swap? Yes.

The Bubble Sort Algorithm Loop over array n-1 times, swapping pairs of entries as needed. [0] [1] [2] [3] [4] [5] Swap? Yes.

The Bubble Sort Algorithm Loop over array n-1 times, swapping pairs of entries as needed. [0] [1] [2] [3] [4] [5] Swap? No.

The Bubble Sort Algorithm Loop over array n-1 times, swapping pairs of entries as needed. [0] [1] [2] [3] [4] [5] Swap? No.

The Bubble Sort Algorithm Continue looping, until done. [0] [1] [2] [3] [4] [5] Swap? Yes.

Bubble sort animation

template void bubble_sort(Item data[ ], size_t n) { size_t i, j; Item temp; if(n < 2) return; // nothing to sort!! for(i = 0; i < n-1; ++i) { for(j = 0; j < n-1;++j) if(data[j] > data[j+1]) // if out of order, swap! { temp = data[j]; data[j] = data[j+1]; data[j+1] = temp; }

template void bubble_sort(Item data[ ], size_t n) { size_t i, j; Item temp; bool swapped = true; if(n < 2) return; // nothing to sort!! for(i = 0; swapped and i < n-1; ++i) {// if no elements swapped in an iteration, // then elements are in order: done! for(swapped = false, j = 0; j < n-1;++j) if(data[j] > data[j+1]) // if out of order, swap! { temp = data[j]; data[j] = data[j+1]; data[j+1] = temp; swapped = true; }

Bubble Sort Time Analysis In O-notation, what is: –Worst case running time for n items? –Average case running time for n items? Steps of algorithm: for i = 0 to n-1 for j =0 to n-2 if key[j] > key[j+1] then swap if no elements swapped in this pass through array, done. otherwise, continue

Bubble Sort Time Analysis In O-notation, what is: –Worst case running time for n items? –Average case running time for n items? Steps of algorithm: for i = 0 to n-1 for j =0 to n-2 if key[j] > key[j+1] then swap if no elements swapped in this pass through array, done. otherwise, continue O(n)

Selection Sort, Insertion Sort, and Bubble Sort all have a worst-case time of O(n 2 ), making them impractical for large arrays. But they are easy to understand, easy to program, easy to debug. Insertion Sort also has good performance when the array is nearly sorted to begin with. Timing and Other Issues

Next class More sophisticated sorting algorithms are needed when good performance is needed in all cases for large arrays. Next class: Merge Sort, Heap Sort. –O(N log N) Review the “recursion algorithm” and “heap structure” we discussed last week.

Merge sort

1. Partitioning: Divide the unsorted list into n sublists, each containing 1 element (a list of 1 element is considered sorted). 2. Merging: Recursively merge sublists to produce new sorted sublists until there is only 1 sublist remaining. This will be the sorted list. Recursion

Main Index Contents 88 The Merge Algorithm Example The merge algorithm takes a sequence of elements in a vector v having index range [first, last). The sequence consists of two ordered sublists separated by an intermediate index, called mid.

Main Index Contents 89 Main Index Contents The Merge Algorithm… (Cont…)

Main Index Contents 90 Main Index Contents The Merge Algorithm… (Cont…)

Main Index Contents 91 The Merge Algorithm… (Cont…)

Merge sort animation

mergeSort()

Main Index Contents 94 Main Index Contents Partitioning and Merging of Sublists in mergeSort()

Complexity of merge sort

Worst, best, average case Complexity: O(n log n) Worst, best, average case Complexity: O(n log n)

Heap sort

Heaps For a maximum heap, the value of a parent is greater than or equal to the value of each of its children. For a minimum heap, the value of the parent is less than or equal to the value of each of its children. We assume that a heap is a maximum heap.

Heap sort 1. Build a heap of N elements – the maximum element is at the top of the heap 2. Perform N Delete operations – the elements are extracted in sorted order

Heap sort animation

Heap sort – Running Time Analysis 1. Build a binary heap of N elements  O(N), see slide 21 of lecture ‘heap’ 2. Perform N Delete operations – Each Delete operation takes O(log N), See slide 23 of lecture ‘heap’  Total: O(N log N) Total time complexity: O(N) + O(N log N)  O(N log N)

Reading Chapter 7