Data Structures and Algorithms Telerik Software Academy

Slides:



Advertisements
Similar presentations
Windows Basic and Dynamic Disk Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator Marian Marinov CEO of 1H Ltd.
Advertisements

Amazon S 3, App Engine Blobstore, Google Cloud Storage, Azure Blobs Svetlin Nakov Telerik Software Academy academy.telerik.com.
RPN and Shunting-yard algorithm Ivaylo Kenov Telerik Software Academy academy.telerik.com Technical Assistant
Shortest paths in edge-weighted digraph Krasin Georgiev Technical University of Sofia g.krasin at gmail com Assistant Professor.
Telerik Software Academy Telerik School Academy.
Asynchronous Programming with C# and WinRT
Brief Overview of Combinations, Permutations and Binary Vectors Data Structures and Algorithms Telerik Software Academy
Telerik School Academy ASP.NET MVC.
Brief Introduction in Problem Solving using Dynamic Programming and Memoization.
Character sequences, C-strings and the C++ String class, Working with Strings Learning & Development Team Telerik Software Academy.
Computation for Physics 計算物理概論 Algorithm. An algorithm is a step-by-step procedure for calculations. Algorithms are used for calculation, data processing,
Done already for your convenience! Telerik School Academy Unity 2D Game Development.
Processing Sequences of Elements Telerik School Academy C# Fundamentals – Part 1.
NoSQL Concepts, Redis, MongoDB, CouchDB
The Business Plan and the Business Model Margarita Antonova Volunteer Telerik Academy academy.telerik.com Business System Analyst Telerik Corporation.
What are ADTs, STL Intro, vector, list, queue, stack Learning & Development Team Telerik Software Academy.
Making JavaScript code by template! Learning & Development Team Telerik Software Academy.
Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training Who, What, Why?
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Processing Matrices and Multidimensional Tables Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Learning & Development Telerik Software Academy.
Reading and Writing Text Files Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Classical OOP in JavaScript Classes and stuff Telerik Software Academy
Optimization problems, Greedy Algorithms, Optimal Substructure and Greedy choice Learning & Development Team Telerik Software.
Using Selenium for Mobile Web Testing Powered by KendoUI Telerik QA Academy Atanas Georgiev Senior QA Engineer KendoUI Team.
NoSQL Concepts, Redis, MongoDB, CouchDB Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
New features: classes, generators, iterators, etc. Telerik Academy Plus JavaScript.Next.
Throwing and Catching Exceptions Tran Anh Tuan Edit from Telerik Software Academy
Loops, Conditional Statements, Functions Tran Anh Tuan Edit from Telerik Academy
Brief Overview of Combinations, Permutations and Binary Vectors Nikolay Kostov Telerik Corporation Technical Trainer.
Private/Public fields, Module, Revealing Module Learning & Development Team Telerik Software Academy.
Building Data-Driven ASP.NET Web Forms Apps Telerik Software Academy ASP.NET Web Forms.
Telerik Software Academy End-to-end JavaScript Applications.
General and reusable solutions to common problems in software design Vasil Dininski Telerik Software Academy academy.telerik.com Intern at Telerik Academy.
Planning and Tracking Software Quality Yordan Dimitrov Telerik Corporation Team Leader, Team Pulse, Team Leader, Team Pulse, Telerik Corporation,
What you need to know Ivaylo Kenov Telerik Corporation Telerik Academy Student.
Data binding concepts, Bindings in WinJS George Georgiev Telerik Software Academy academy.telerik.com Technical Trainer itgeorge.net.
Pavel Kolev Telerik Software Academy Senior.Net Developer and Trainer
Sorting and Searching Algorithms
Objects, Properties, Primitive and Reference Types Learning & Development Team Telerik Software Academy.
When and How to Refactor? Refactoring Patterns Alexander Vakrilov Telerik Corporation Senior Developer and Team Leader.
Free Training and Job for Software Engineers Svetlin Nakov, PhD Manager Technical Training Telerik Corp. Telerik Software Academy.
Access to known folders, using pickers, writing to and reading from files, caching files for future access George Georgiev Telerik Software Academy academy.telerik.com.
Doing the Canvas the "easy way"! Learning & Development Telerik Software Academy.
Creating and Running Your First C# Program Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical Training
Subroutines in Computer Programming Telerik School Academy C# Fundamentals – Part 1.
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.
Correctly Formatting the Source Code Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Data Types, Primitive Types in C++, Variables – Declaration, Initialization, Scope Telerik Software Academy academy.telerik.com Learning and Development.
The past, the present, the future Learning & Development Team Telerik Software Academy.
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Connecting, Queries, Best Practices Tran Anh Tuan Edit from Telerik Software Academy
Processing Sequences of Elements Telerik Software Academy C# Fundamentals – Part 2.
Telerik JavaScript Framework Telerik Software Academy Hybrid Mobile Applications.
Building Rock-Solid Software Nikolay Kostov Telerik Software Academy academy.telerik.com Senior Software Developer and Technical Trainer
Telerik Software Academy Databases.
ICS201 Lecture 21 : Sorting King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
Things start to get serious Telerik Software Academy JavaScript OOP.
Learning & Development Mobile apps for iPhone & iPad.
Processing Matrices and Multidimensional Tables Telerik Software Academy C# Fundamentals – Part 2.
Nikolay Kostov Telerik Software Academy academy.telerik.com Team Lead, Senior Developer and Trainer
Functions and Function Expressions Closures, Function Scope, Nested Functions Telerik Software Academy
Implementing Control Logic in C# Svetlin Nakov Telerik Software Academy academy.telerik.com Manager Technical trainer
Inheritance, Abstraction, Encapsulation, Polymorphism Telerik Software Academy Mobile apps for iPhone & iPad.
Mocking tools for easier unit testing Telerik Software Academy High Quality Code.
What why and how? Telerik School Academy Unity 2D Game Development.
Windows Security Model Borislav Varadinov Telerik Software Academy academy.telerik.com System Administrator
Computational Complexity, Choosing Data Structures Svetlin Nakov Telerik Software Academy Manager Technical Trainer
Lists, Stacks, Queues Svetlin Nakov Telerik Software Academy Manager Technical Trainer
Sorting and Searching Algorithms
Presentation transcript:

Data Structures and Algorithms Telerik Software Academy

 Sorting  Sorting and classification  Review of the most popular sorting algorithms  Searching  Linear search  Binary search  Interpolation search  Shuffling 2

 Sorting algorithm  An algorithm that puts elements of a list in a certain order (most common lexicographically)  More formally:  The output is in some (non-decreasing) order  The output is a permutation of the input  Efficient sorting is important for  Producing human-readable output  Canonicalizing data  Optimizing the use of other algorithms  Sorting presents many important techniques 4

 Sorting algorithms are often classified by  Computational complexity  worst, average and best behavior  Memory usage  Recursive or non-recursive  Stability  Whether or not they are a comparison sort  General method  insertion, exchange (bubble sort and quicksort), selection (heapsort), merging, serial or parallel… 5

 Stable sorting algorithms  Maintain the relative order of records with equal values  If two items compare as equal, then their relative order will be preserved  When sorting only part of the data is examined when determining the sort order 6

 Very simple and very inefficient algorithm  Best, worst and average case: n 2  Memory: 1 (constant, only for the min element)  Stable: No  Method: Selection  for (j = 0; j < n-1; j++) { /* find the min element in the unsorted a[j.. n-1] */ /* find the min element in the unsorted a[j.. n-1] */ iMin = j; iMin = j; for ( i = j+1; i < n; i++) { for ( i = j+1; i < n; i++) { if (a[i] < a[iMin]) iMin = i; if (a[i] < a[iMin]) iMin = i; } if (iMin != j) swap(a[j], a[iMin]); if (iMin != j) swap(a[j], a[iMin]);}

 Repeatedly stepping through the list, comparing each pair of adjacent items and swap them if they are in the wrong order  Best case: n, worst and average case: n 2  Memory: 1, Stable: Yes, Method: Exchanging  8

 Builds the final sorted array one item at a time  Best case: n, worst and average case: n 2  Memory: 1, Stable: Yes, Method: Insertion  for i ← 1 to i ← length(A)-1 { valueToInsert ← A[i] valueToInsert ← A[i] holePos ← i holePos ← i while holePos > 0 and valueToInsert 0 and valueToInsert < A[holePos - 1] { A[holePos] ← A[holePos - 1] // shift the larger value up A[holePos] ← A[holePos - 1] // shift the larger value up holePos ← holePos - 1 // move the hole position down holePos ← holePos - 1 // move the hole position down } A[holePos] ← valueToInsert A[holePos] ← valueToInsert}

 First divides a large list into two smaller sub- lists then recursively sort the sub-lists  Best and average case: n*log(n), worst: n 2  Memory: log(n) stack space  Stable: Depends  Method: Partitioning  Stable implementation

 Conceptually, a merge sort works as follows  Divide the unsorted list into n sublists, each containing 1 element (list of 1 element is sorted)  Repeatedly merge sublists to produce new sublists until there is only 1 sublist remaining  Best, average and worst case: n*log(n)  Memory: Depends; worst case is n  Stable: Yes; Method: Merging  Highly parallelizable (up to O(log(n) ) using the Three Hungarian's Algorithm 

12 function merge_sort(list m) // if list size is 0 (empty) or 1, consider it sorted // if list size is 0 (empty) or 1, consider it sorted // (using less than or equal prevents infinite recursion for a zero length m) // (using less than or equal prevents infinite recursion for a zero length m) if length(m) <= 1 if length(m) <= 1 return m return m // else list size is > 1, so split the list into two sublists // else list size is > 1, so split the list into two sublists var list left, right var list left, right var integer middle = length(m) / 2 var integer middle = length(m) / 2 for each x in m before middle for each x in m before middle add x to left add x to left for each x in m after or equal middle for each x in m after or equal middle add x to right add x to right // recursively call merge_sort() to further split each sublist // recursively call merge_sort() to further split each sublist // until sublist size is 1 // until sublist size is 1 left = merge_sort(left) left = merge_sort(left) right = merge_sort(right) right = merge_sort(right) // merge the sublists returned from prior calls to merge_sort() // merge the sublists returned from prior calls to merge_sort() // and return the resulting merged sublist // and return the resulting merged sublist return merge(left, right) return merge(left, right)

13 function merge(left, right) var list result var list result while length(left) > 0 or length(right) > 0 while length(left) > 0 or length(right) > 0 if length(left) > 0 and length(right) > 0 if length(left) > 0 and length(right) > 0 if first(left) <= first(right) if first(left) <= first(right) append first(left) to result append first(left) to result left = rest(left) left = rest(left) else else append first(right) to result append first(right) to result right = rest(right) right = rest(right) else if length(left) > 0 else if length(left) > 0 append first(left) to result append first(left) to result left = rest(left) left = rest(left) else if length(right) > 0 else if length(right) > 0 append first(right) to result append first(right) to result right = rest(right) right = rest(right) end while end while return result return result

 Specialized tree-based data structure that satisfies the heap property:  Parent nodes are always greater (less) than or equal to the children  No implied ordering between siblings or cousins  en.wikipedia.org/wiki/Heap_(data_structure) en.wikipedia.org/wiki/Heap_(data_structure) 14 find-minΘ(1) delete-minΘ(log n) insertΘ(log n) decrease-keyΘ(log n) mergeΘ(n)

 Can be divided into two parts  In the first step, a heap is built out of the data  A sorted array is created by repeatedly removing the largest element from the heap  Best, average and worst case: n*log(n)  Memory: Constant - O(1)  Stable: No  Method: Selection 

 Algorithm for sorting a collection of objects according to keys that are small integers  Not a comparison sort  Average case: n + r  Worst case: n + r  r is the range of numbers to be sorted  Stable: Yes  Memory: n + r 

 Partitioning an array into a number of buckets  Each bucket is then sorted individually  Not a comparison sort  Average case: n + k  k = the number of buckets  Worst case: n 2 * k  Stable: Yes  Memory: n * k 

 There are hundreds of sorting algorithms 18 NameBestAverageWorstMemoryStableMethod Selection sort n2n2n2n2 n2n2n2n2 n2n2n2n21 NoSelection Bubble sortn n2n2n2n2 n2n2n2n21 YesExchanging Insertion sortn n2n2n2n2 n2n2n2n21 YesInsertion Quicksortn*log(n)n*log(n) n2n2n2n2log(n) DependsPartitioning Merge sortn*log(n)n*log(n)n*log(n) n Depends worst case is n YesMerging Heapsortn*log(n)n*log(n)n*log(n)1 NoSelection Bogosortnn*n!n*n!1 NoLuck …………… ……

 An algorithm for finding an item with specified properties among a collection of items  Different types of searching algorithms  For virtual search spaces  satisfy specific mathematical equations  try to exploit partial knowledge about structure  For sub-structures of a given structure  graph, a string, a finite group  Search for the max (min) of a function  etc. 20

 Method for finding a particular value in a list  Checking every one of the elements  One at a time in sequence  Until the desired one is found  Worst and average performance: O(n) 21 for each item in the list: for each item in the list: if that item has the desired value, if that item has the desired value, stop the search and return the item's location. stop the search and return the item's location. return nothing. return nothing.

 Finds the position of a specified value within a sorted data structure  In each step, compare the input with the middle  The algorithm repeats its action to the left or right sub-structure  Average performance: O(log(n)) 22

23 int binary_search(int A[], int key, int imin, int imax) { if (imax < imin) if (imax < imin) // set is empty, so return value showing not found // set is empty, so return value showing not found return KEY_NOT_FOUND; return KEY_NOT_FOUND; else else { // calculate midpoint to cut set in half // calculate midpoint to cut set in half int imid = midpoint(imin, imax); int imid = midpoint(imin, imax); if (A[imid] > key) if (A[imid] > key) // key is in lower subset // key is in lower subset return binary_search(A, key, imin, imid-1); return binary_search(A, key, imin, imid-1); else if (A[imid] < key) else if (A[imid] < key) // key is in upper subset // key is in upper subset return binary_search(A, key, imid+1, imax); return binary_search(A, key, imid+1, imax); else else // key has been found // key has been found return imid; return imid; }}

24 int binary_search(int A[], int key, int imin, int imax) { // continue searching while [imin,imax] is not empty // continue searching while [imin,imax] is not empty while (imax >= imin) while (imax >= imin) { /* calculate the midpoint for roughly equal partition */ /* calculate the midpoint for roughly equal partition */ int imid = midpoint(imin, imax); int imid = midpoint(imin, imax); // determine which subarray to search // determine which subarray to search if (A[imid] < key) if (A[imid] < key) // change min index to search upper subarray // change min index to search upper subarray imin = imid + 1; imin = imid + 1; else if (A[imid] > key) else if (A[imid] > key) // change max index to search lower subarray // change max index to search lower subarray imax = imid - 1; imax = imid - 1; else else // key found at index imid // key found at index imid return imid; return imid; } return KEY_NOT_FOUND; return KEY_NOT_FOUND;}

 An algorithm for searching for a given key value in an indexed array that has been ordered by the values of the key  Parallels how humans search through a telephone book  Calculates where in the remaining search space the sought item might be  Binary search always chooses the middle element  Average case: log(log(n)), Worst case: O(n) 

26 public int interpolationSearch(int[] sortedArray, int toFind){ // Returns index of toFind in sortedArray, or -1 if not found // Returns index of toFind in sortedArray, or -1 if not found int low = 0; int low = 0; int high = sortedArray.length - 1; int high = sortedArray.length - 1; int mid; int mid; while(sortedArray[low] = toFind) { while(sortedArray[low] = toFind) { mid = low + ((toFind - sortedArray[low]) * (high - low)) / mid = low + ((toFind - sortedArray[low]) * (high - low)) / (sortedArray[high] - sortedArray[low]); (sortedArray[high] - sortedArray[low]); // out of range is possible here // out of range is possible here if (sortedArray[mid] < toFind) if (sortedArray[mid] < toFind) low = mid + 1; low = mid + 1; else if (sortedArray[mid] > toFind) else if (sortedArray[mid] > toFind) high = mid - 1; high = mid - 1; else else return mid; return mid; } if (sortedArray[low] == toFind) return low; if (sortedArray[low] == toFind) return low; else return -1; // Not found else return -1; // Not found}

 A procedure used to randomize the order of items in a collection  Generating random permutation 

29 public static IEnumerable Shuffle (this IEnumerable source) { var array = source.ToArray(); var array = source.ToArray(); var n = array.Length; var n = array.Length; for (var i = 0; i < n; i++) for (var i = 0; i < n; i++) { // Exchange a[i] with random element in a[i..n-1] // Exchange a[i] with random element in a[i..n-1] int r = i + RandomProvider.Instance.Next(0, n - i); int r = i + RandomProvider.Instance.Next(0, n - i); var temp = array[i]; var temp = array[i]; array[i] = array[r]; array[i] = array[r]; array[r] = temp; array[r] = temp; } return array; return array;} public static class RandomProvider { private static Random Instance = new Random(); private static Random Instance = new Random();}

форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен SEO курс - оптимизация за търсачки уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop уроци по програмиране и уеб дизайн за ученици ASP.NET MVC курс – HTML, SQL, C#,.NET, ASP.NET MVC безплатен курс "Разработка на софтуер в cloud среда" BG Coder - онлайн състезателна система - online judge курсове и уроци по програмиране, книги – безплатно от Наков безплатен курс "Качествен програмен код" алго академия – състезателно програмиране, състезания ASP.NET курс - уеб програмиране, бази данни, C#,.NET, ASP.NET курсове и уроци по програмиране – Телерик академия курс мобилни приложения с iPhone, Android, WP7, PhoneGap free C# book, безплатна книга C#, книга Java, книга C# Николай Костов - блог за програмиране

 Open Sorting-and-Searching-Algorithms- Homework.zip and: 1.Implement SelectionSorter.Sort() method using selection sort algorithm 2.Implement Quicksorter.Sort() method using quicksort algorithm 3.Implement MergeSorter.Sort() method using merge sort algorithm 4.Implement SortableCollection.LinearSearch() method using linear search  Don’t use built-in search methods. Write your own. 31

5.Implement SortableCollection.BinarySearch() method using binary search algorithm 6.Implement SortableCollection.Shuffle() method using shuffle algorithm of your choice  Document what is the complexity of the algorithm 7.* Unit test sorting algorithms  SelectionSorter.Sort()  Quicksorter.Sort()  MergeSorter.Sort() 8.* Unit test searching algorithms  SortableCollection.LinearSearch()  SortableCollection.BinarySearch() 32

 C# Telerik Academy  csharpfundamentals.telerik.com csharpfundamentals.telerik.com  Telerik Software Academy  academy.telerik.com academy.telerik.com  Telerik Facebook  facebook.com/TelerikAcademy facebook.com/TelerikAcademy  Telerik Software Academy Forums  forums.academy.telerik.com forums.academy.telerik.com 33