SlideShare a Scribd company logo
Searching and sorting arrays combinatorial samples Algorithms with Java
Contents Algorithms and thinking Sorting Searching Combinatorial
What is “algorithm”? An effective method for solving a problem expressed in a finite sequence of steps Used for calculations, data processing, solving daily problems via Wikipedia
More about algorithms There are common algorithms solving common problems The more you think algorithmically, the easier you solve real world issues Complex algorithms constructed on simple ones
Similarities with Maths Systems created from primitives Abstraction reduces complexity Underlying logic backend Common way of thinking, but not necessarily related
Complexity of algorithms Two functions: Time complexity Space complexity Common measuring characteristics Noted with a big “O” letter
Examples of complexity O(1) – constant time O(n) – linear time O(n 2 ) – square time O(log n) – logarithmic time O(2 n ) – exponential time
How to Measure “O” on iterations Direct access means complexity of 1 1 to N for loop is O(n) Three inner loops from 1 to n is O(n 3 ) Measurement helps improving algorithms
Sorting To arrange a common subset in a given order alphabetically by increasing number, size, weight... Useful for searching later
Different methodologies Different sorting algorithms: bubble sort quick sort insertion sort... Different min/max/avg complexity
Bubble sort Easiest and shortest Average O(n2) performance Compares each pair and swaps where needed
Bubble sort: steps Input random array Start first round for sorting Create inner loop to check every element with its neighbor If order is wrong, swap elements
Bubble sort – Example Iterate array twice and check neighbors  public static void bubble(int[] array) { for(int i = 0; i < array.length; i++) { for(int j = 0; j < array.length-1; j++) { if(array[j] > array[j+1]) { int tmp = array[j]; array[j] = array[j+1]; array[j+1] = tmp; } } } }
Bubble sort Live Demo
Insertion sort Simple to implement Works fast for small amounts Effective for partially sorted arrays Required memory space is O(1)
Insertion sort: steps Consider some part of the array is sorted Loop only non-sorted part Get lonely elements and insert them in the sorted row
Insertion sort - Example Insertion sort example for(int i = 1; i < array.length; i++) { // take current element and position int current = array[i]; int dec = i; while(dec > 0 && current < array[dec-1]) { array[dec] = array[dec-1]; dec = dec-1; } array[dec] = current; }
Insertion sort Live Demo
Quick sort Best performance in most cases Harder to implement Recursive implementation
Quick sort: steps Take the whole array and a median  Smaller numbers – on the left of median, bigger – on the right (or vice verse) Call the same function on left and right parts Granular sort of small chunks
Quick sort - Example Quick sort pseudo call quick_sort(low, high); left = 0; right = n; mid = a[(left+right)/2]; while left <= right: while a[left] < mid -> left++; while a[right] > mid -> right--; if left <= right: swap(left, right); left++; right--; quicksort(low, right); quicksort(left, high);
Quick sort Live Demo
Searching Finding an element in a given row Different approaches depending on the input Samples with sequential check or binary searching algorithm
Binary search Works only on ordered (sorted) arrays Highly effective and reduced complexity Binary algorithms are used in databases and structures for optimizations
Binary search: steps Get a sorted array and select a number Search array from 0 to N Chose a median from the row and find whether the number in question is on the left or on the right If smaller/bigger number, call the function with 0-med or med-N range ... (recursively)
Binary search - Example Binary search code public static int binarySearch(int[] array, int low, int high, int number) {   if (low < high) {   int middle = (low + high) / 2;    if (number < array[middle]) {   return binarySearch(array, low, middle, number);   } else if (number > array[middle]) {   return binarySearch(array, middle+1, high, number);   } else {   return middle; // real result    }   }   return -1; // element not found }
Combinatorial Computing different situations Three main divisions: permutations combinations variations
Combinatorial (2)  Permutations – all sequences without repetitive digits Variations – all sequences consisting of all digits in the range Combinations – all sequences with no reversal (1, 2) or (2,1) but not both
Permutation For a given number n create n-dimensional array with ordered permutations Create an array with digits 1 to n Permutations are n!
Permutations (2) Pseudo code for i=n to 0: if a[i] > a[i-1]: for j=i to n: find min(a[j]) > a[i-1]; swap(a[i-1], a[j]); sort(a[i], n);
Permutations Live Demo
Summary Algorithm is a step list that solves a problem Arrays could be placeholders for data We could sort arrays in different ways and search with different complexity Sequences could be arranged in different combinations
Exercises Write a program that allocates array of 20 integers and initializes each element by its index multiplied by 5. Print the obtained array on the console. Write a program that reads two arrays from the console and compares them for equality. Write a program that compares two  char  arrays lexicographically (letter by letter). Write a program that finds the maximal increasing sequence of equal elements in an array. Example: {3,  2, 3, 4 , 2, 2, 4}    {2, 3, 4}.
Exercises Write a program that reads two integer numbers N and K and an array of N elements from the console. Find in the array those K elements that have maximal sum. Sorting an array means to arrange its elements in increasing order. Write a program to sort an array. Use the &quot;selection sort&quot; algorithm: Find the smallest element, move it at the first position, find the smallest from the rest, move it at second position, etc.
Exercises (6) * Write a program that sorts an  int  array using the  quick sort  algorithm. Write a program that creates an array containing all letters from the alphabet. Read a word from the console and print the index of each letter in the array. * Write a program that finds the index of given element in a sorted  int  array by using the  binary search  algorithm. * Write a program that sorts an  int  array using the  merge sort  algorithm.
Homework Write a program that finds all prime numbers in the range [1...10 000 000]. Use the  sieve of Eratosthenes  algorithm. Write a program that reads two numbers  n  and  k  and generates all the variations of  k  elements from the set [ 1 .. n ]. Example: n = 3, k = 2    {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3} Write a program that reads a number  n  and generates all the permutations of the numbers 1..n. Example: n = 3    {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
Homework (2) Write a program that fills and prints a matrix (n, n) as shown below: (examples for n = 4) a) b) c) d) 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 7 11 14 16 4 8 12 15 2 5 9 13 1 3 6 10 1 8 9 16 2 7 10 15 3 6 11 14 4 5 12 13 1 12 11 10 2 13 16 9 3 14 15 8 4 5 6 7
Homework (3) * Write a program that finds the largest area of equal neighbor elements in a rectangular matrix and prints its size. Example: Hint: you can use the algorithm &quot; Depth-first search &quot; or &quot; Breadth-first search &quot;. 13 1 3 2 2 2 4 3 3 3 2 4 4 4 3 1 2 3 3 4 3 1 3 3 1 4 3 3 3 1 1

More Related Content

What's hot (20)

Heap sort
Heap sortHeap sort
Heap sort
Ayesha Tahir
 
Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
samairaakram
 
Extensible hashing
Extensible hashingExtensible hashing
Extensible hashing
rajshreemuthiah
 
Recognition-of-tokens
Recognition-of-tokensRecognition-of-tokens
Recognition-of-tokens
Dattatray Gandhmal
 
Heap tree
Heap treeHeap tree
Heap tree
Shankar Bishnoi
 
Hashing
HashingHashing
Hashing
Amar Jukuntla
 
Operators in java
Operators in javaOperators in java
Operators in java
yugandhar vadlamudi
 
Chapter-7 Relational Calculus
Chapter-7 Relational CalculusChapter-7 Relational Calculus
Chapter-7 Relational Calculus
Kunal Anand
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
Kuppusamy P
 
Operator precedence
Operator precedenceOperator precedence
Operator precedence
Akshaya Arunan
 
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSINGINTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
Aaqib Hussain
 
Principal source of optimization in compiler design
Principal source of optimization in compiler designPrincipal source of optimization in compiler design
Principal source of optimization in compiler design
Rajkumar R
 
Packages in java
Packages in javaPackages in java
Packages in java
Kavitha713564
 
Database Models.pdf
Database Models.pdfDatabase Models.pdf
Database Models.pdf
nirmalraj murugaiyan
 
Map reduce in BIG DATA
Map reduce in BIG DATAMap reduce in BIG DATA
Map reduce in BIG DATA
GauravBiswas9
 
Identifying classes and objects ooad
Identifying classes and objects ooadIdentifying classes and objects ooad
Identifying classes and objects ooad
Melba Rosalind
 
Iv unit-fuzzification and de-fuzzification
Iv unit-fuzzification and de-fuzzificationIv unit-fuzzification and de-fuzzification
Iv unit-fuzzification and de-fuzzification
kypameenendranathred
 
Java: The Complete Reference, Eleventh Edition
Java: The Complete Reference, Eleventh EditionJava: The Complete Reference, Eleventh Edition
Java: The Complete Reference, Eleventh Edition
moxuji
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
kunal kishore
 
Automata theory
Automata theoryAutomata theory
Automata theory
Pardeep Vats
 
Heap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithmsHeap Sort in Design and Analysis of algorithms
Heap Sort in Design and Analysis of algorithms
samairaakram
 
Chapter-7 Relational Calculus
Chapter-7 Relational CalculusChapter-7 Relational Calculus
Chapter-7 Relational Calculus
Kunal Anand
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
Kuppusamy P
 
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSINGINTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
Aaqib Hussain
 
Principal source of optimization in compiler design
Principal source of optimization in compiler designPrincipal source of optimization in compiler design
Principal source of optimization in compiler design
Rajkumar R
 
Map reduce in BIG DATA
Map reduce in BIG DATAMap reduce in BIG DATA
Map reduce in BIG DATA
GauravBiswas9
 
Identifying classes and objects ooad
Identifying classes and objects ooadIdentifying classes and objects ooad
Identifying classes and objects ooad
Melba Rosalind
 
Iv unit-fuzzification and de-fuzzification
Iv unit-fuzzification and de-fuzzificationIv unit-fuzzification and de-fuzzification
Iv unit-fuzzification and de-fuzzification
kypameenendranathred
 
Java: The Complete Reference, Eleventh Edition
Java: The Complete Reference, Eleventh EditionJava: The Complete Reference, Eleventh Edition
Java: The Complete Reference, Eleventh Edition
moxuji
 
Operators in java presentation
Operators in java presentationOperators in java presentation
Operators in java presentation
kunal kishore
 

Viewers also liked (11)

Overriding methods
Overriding methodsOverriding methods
Overriding methods
Muthukumaran Subramanian
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Ch13 Binary Search Tree
Ch13 Binary Search TreeCh13 Binary Search Tree
Ch13 Binary Search Tree
leminhvuong
 
Java keywords
Java keywordsJava keywords
Java keywords
Ravi_Kant_Sahu
 
Binary search
Binary searchBinary search
Binary search
Gaurav Solanki
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary Search
Reem Alattas
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
OUM SAOKOSAL
 
Super keyword in java
Super keyword in javaSuper keyword in java
Super keyword in java
Hitesh Kumar
 
Ch13 Binary Search Tree
Ch13 Binary Search TreeCh13 Binary Search Tree
Ch13 Binary Search Tree
leminhvuong
 
Linear Search & Binary Search
Linear Search & Binary SearchLinear Search & Binary Search
Linear Search & Binary Search
Reem Alattas
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
Eduardo Bergavera
 
encapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloadingencapsulation, inheritance, overriding, overloading
encapsulation, inheritance, overriding, overloading
Shivam Singhal
 
Object Oriented Programming Concepts
Object Oriented Programming ConceptsObject Oriented Programming Concepts
Object Oriented Programming Concepts
thinkphp
 
Chapter 9 Abstract Class
Chapter 9 Abstract ClassChapter 9 Abstract Class
Chapter 9 Abstract Class
OUM SAOKOSAL
 
Ad

Similar to Algorithms with-java-advanced-1.0 (20)

Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
Abdul Khan
 
sorting
sortingsorting
sorting
Ravirajsinh Chauhan
 
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sortsearch_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
Kanupriya731200
 
search_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sortsearch_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sort
Shanmuganathan C
 
2.Problem Solving Techniques and Data Structures.pptx
2.Problem Solving Techniques and Data Structures.pptx2.Problem Solving Techniques and Data Structures.pptx
2.Problem Solving Techniques and Data Structures.pptx
Ganesh Bhosale
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
arnold 7490
 
Advanced Topics In Java Core Concepts In Data Structures Noel Kalicharan
Advanced Topics In Java Core Concepts In Data Structures Noel KalicharanAdvanced Topics In Java Core Concepts In Data Structures Noel Kalicharan
Advanced Topics In Java Core Concepts In Data Structures Noel Kalicharan
fickolatigo
 
Sortings .pptx
Sortings .pptxSortings .pptx
Sortings .pptx
MuhammadSheraz836877
 
01 analysis-of-algorithms
01 analysis-of-algorithms01 analysis-of-algorithms
01 analysis-of-algorithms
Noushadur Shoukhin
 
Searching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresSearching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structures
PRIANKA R
 
Data structure using c module 3
Data structure using c module 3Data structure using c module 3
Data structure using c module 3
smruti sarangi
 
Recursion.pptx
Recursion.pptxRecursion.pptx
Recursion.pptx
Bharati Vidyapeeth COE, Navi Mumbai
 
Sorting and searching
Sorting and searchingSorting and searching
Sorting and searching
kalyanineve
 
C Language Unit-6
C Language Unit-6C Language Unit-6
C Language Unit-6
kasaragadda srinivasrao
 
Sorting2
Sorting2Sorting2
Sorting2
Saurabh Mishra
 
Unit6 jwfiles
Unit6 jwfilesUnit6 jwfiles
Unit6 jwfiles
mrecedu
 
Sorting
SortingSorting
Sorting
invertis university
 
UNIT I- Sesgfnbghnghnghmghmhgmhmhsion 4.pptx
UNIT I- Sesgfnbghnghnghmghmhgmhmhsion 4.pptxUNIT I- Sesgfnbghnghnghmghmhgmhmhsion 4.pptx
UNIT I- Sesgfnbghnghnghmghmhgmhmhsion 4.pptx
akashkhedar262
 
Unit 7 sorting
Unit 7   sortingUnit 7   sorting
Unit 7 sorting
kalyanineve
 
L 14-ct1120
L 14-ct1120L 14-ct1120
L 14-ct1120
Zia Ush Shamszaman
 
Algorithm & data structures lec4&5
Algorithm & data structures lec4&5Algorithm & data structures lec4&5
Algorithm & data structures lec4&5
Abdul Khan
 
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sortsearch_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
Kanupriya731200
 
search_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sortsearch_sort Search sortSearch sortSearch sortSearch sort
search_sort Search sortSearch sortSearch sortSearch sort
Shanmuganathan C
 
2.Problem Solving Techniques and Data Structures.pptx
2.Problem Solving Techniques and Data Structures.pptx2.Problem Solving Techniques and Data Structures.pptx
2.Problem Solving Techniques and Data Structures.pptx
Ganesh Bhosale
 
Advanced Topics In Java Core Concepts In Data Structures Noel Kalicharan
Advanced Topics In Java Core Concepts In Data Structures Noel KalicharanAdvanced Topics In Java Core Concepts In Data Structures Noel Kalicharan
Advanced Topics In Java Core Concepts In Data Structures Noel Kalicharan
fickolatigo
 
Searching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structuresSearching and sorting Techniques in Data structures
Searching and sorting Techniques in Data structures
PRIANKA R
 
Data structure using c module 3
Data structure using c module 3Data structure using c module 3
Data structure using c module 3
smruti sarangi
 
Sorting and searching
Sorting and searchingSorting and searching
Sorting and searching
kalyanineve
 
Unit6 jwfiles
Unit6 jwfilesUnit6 jwfiles
Unit6 jwfiles
mrecedu
 
UNIT I- Sesgfnbghnghnghmghmhgmhmhsion 4.pptx
UNIT I- Sesgfnbghnghnghmghmhgmhmhsion 4.pptxUNIT I- Sesgfnbghnghnghmghmhgmhmhsion 4.pptx
UNIT I- Sesgfnbghnghnghmghmhgmhmhsion 4.pptx
akashkhedar262
 
Ad

More from BG Java EE Course (20)

Rich faces
Rich facesRich faces
Rich faces
BG Java EE Course
 
JSP Custom Tags
JSP Custom TagsJSP Custom Tags
JSP Custom Tags
BG Java EE Course
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
BG Java EE Course
 
JSTL
JSTLJSTL
JSTL
BG Java EE Course
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
BG Java EE Course
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
BG Java EE Course
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
BG Java EE Course
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
CSS
CSSCSS
CSS
BG Java EE Course
 
HTML: Tables and Forms
HTML: Tables and FormsHTML: Tables and Forms
HTML: Tables and Forms
BG Java EE Course
 
HTML Fundamentals
HTML FundamentalsHTML Fundamentals
HTML Fundamentals
BG Java EE Course
 
WWW and HTTP
WWW and HTTPWWW and HTTP
WWW and HTTP
BG Java EE Course
 
JavaScript and jQuery Fundamentals
JavaScript and jQuery FundamentalsJavaScript and jQuery Fundamentals
JavaScript and jQuery Fundamentals
BG Java EE Course
 
Creating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSSCreating Web Sites with HTML and CSS
Creating Web Sites with HTML and CSS
BG Java EE Course
 
Processing XML with Java
Processing XML with JavaProcessing XML with Java
Processing XML with Java
BG Java EE Course
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
BG Java EE Course
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
BG Java EE Course
 
Introduction to-sql
Introduction to-sqlIntroduction to-sql
Introduction to-sql
BG Java EE Course
 
Introduction to-RDBMS-systems
Introduction to-RDBMS-systemsIntroduction to-RDBMS-systems
Introduction to-RDBMS-systems
BG Java EE Course
 

Recently uploaded (20)

Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Creating an Accessible Future-How AI-powered Accessibility Testing is Shaping...
Impelsys Inc.
 
Edge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdfEdge-banding-machines-edgeteq-s-200-en-.pdf
Edge-banding-machines-edgeteq-s-200-en-.pdf
AmirStern2
 
Oracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization ProgramOracle Cloud and AI Specialization Program
Oracle Cloud and AI Specialization Program
VICTOR MAESTRE RAMIREZ
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean accountYour startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Crypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdfCrypto Super 500 - 14th Report - June2025.pdf
Crypto Super 500 - 14th Report - June2025.pdf
Stephen Perrenod
 
Secure Access with Azure Active Directory
Secure Access with Azure Active DirectorySecure Access with Azure Active Directory
Secure Access with Azure Active Directory
VICTOR MAESTRE RAMIREZ
 
If You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FMEIf You Use Databricks, You Definitely Need FME
If You Use Databricks, You Definitely Need FME
Safe Software
 
Oracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI FoundationsOracle Cloud Infrastructure AI Foundations
Oracle Cloud Infrastructure AI Foundations
VICTOR MAESTRE RAMIREZ
 
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOMEstablish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Establish Visibility and Manage Risk in the Supply Chain with Anchore SBOM
Anchore
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
Down the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training RoadblocksDown the Rabbit Hole – Solving 5 Training Roadblocks
Down the Rabbit Hole – Solving 5 Training Roadblocks
Rustici Software
 
June Patch Tuesday
June Patch TuesdayJune Patch Tuesday
June Patch Tuesday
Ivanti
 
How to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptxHow to Detect Outliers in IBM SPSS Statistics.pptx
How to Detect Outliers in IBM SPSS Statistics.pptx
Version 1 Analytics
 
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely Demo Showcase: Powering ServiceNow Discovery with Precisely Ironstr...
Precisely
 
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025Developing Schemas with FME and Excel - Peak of Data & AI 2025
Developing Schemas with FME and Excel - Peak of Data & AI 2025
Safe Software
 
Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.Introduction to Internet of things .ppt.
Introduction to Internet of things .ppt.
hok12341073
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy SurveyTrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdfHow Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
How Advanced Environmental Detection Is Revolutionizing Oil & Gas Safety.pdf
Rejig Digital
 

Algorithms with-java-advanced-1.0

  • 1. Searching and sorting arrays combinatorial samples Algorithms with Java
  • 2. Contents Algorithms and thinking Sorting Searching Combinatorial
  • 3. What is “algorithm”? An effective method for solving a problem expressed in a finite sequence of steps Used for calculations, data processing, solving daily problems via Wikipedia
  • 4. More about algorithms There are common algorithms solving common problems The more you think algorithmically, the easier you solve real world issues Complex algorithms constructed on simple ones
  • 5. Similarities with Maths Systems created from primitives Abstraction reduces complexity Underlying logic backend Common way of thinking, but not necessarily related
  • 6. Complexity of algorithms Two functions: Time complexity Space complexity Common measuring characteristics Noted with a big “O” letter
  • 7. Examples of complexity O(1) – constant time O(n) – linear time O(n 2 ) – square time O(log n) – logarithmic time O(2 n ) – exponential time
  • 8. How to Measure “O” on iterations Direct access means complexity of 1 1 to N for loop is O(n) Three inner loops from 1 to n is O(n 3 ) Measurement helps improving algorithms
  • 9. Sorting To arrange a common subset in a given order alphabetically by increasing number, size, weight... Useful for searching later
  • 10. Different methodologies Different sorting algorithms: bubble sort quick sort insertion sort... Different min/max/avg complexity
  • 11. Bubble sort Easiest and shortest Average O(n2) performance Compares each pair and swaps where needed
  • 12. Bubble sort: steps Input random array Start first round for sorting Create inner loop to check every element with its neighbor If order is wrong, swap elements
  • 13. Bubble sort – Example Iterate array twice and check neighbors public static void bubble(int[] array) { for(int i = 0; i < array.length; i++) { for(int j = 0; j < array.length-1; j++) { if(array[j] > array[j+1]) { int tmp = array[j]; array[j] = array[j+1]; array[j+1] = tmp; } } } }
  • 15. Insertion sort Simple to implement Works fast for small amounts Effective for partially sorted arrays Required memory space is O(1)
  • 16. Insertion sort: steps Consider some part of the array is sorted Loop only non-sorted part Get lonely elements and insert them in the sorted row
  • 17. Insertion sort - Example Insertion sort example for(int i = 1; i < array.length; i++) { // take current element and position int current = array[i]; int dec = i; while(dec > 0 && current < array[dec-1]) { array[dec] = array[dec-1]; dec = dec-1; } array[dec] = current; }
  • 19. Quick sort Best performance in most cases Harder to implement Recursive implementation
  • 20. Quick sort: steps Take the whole array and a median Smaller numbers – on the left of median, bigger – on the right (or vice verse) Call the same function on left and right parts Granular sort of small chunks
  • 21. Quick sort - Example Quick sort pseudo call quick_sort(low, high); left = 0; right = n; mid = a[(left+right)/2]; while left <= right: while a[left] < mid -> left++; while a[right] > mid -> right--; if left <= right: swap(left, right); left++; right--; quicksort(low, right); quicksort(left, high);
  • 23. Searching Finding an element in a given row Different approaches depending on the input Samples with sequential check or binary searching algorithm
  • 24. Binary search Works only on ordered (sorted) arrays Highly effective and reduced complexity Binary algorithms are used in databases and structures for optimizations
  • 25. Binary search: steps Get a sorted array and select a number Search array from 0 to N Chose a median from the row and find whether the number in question is on the left or on the right If smaller/bigger number, call the function with 0-med or med-N range ... (recursively)
  • 26. Binary search - Example Binary search code public static int binarySearch(int[] array, int low, int high, int number) { if (low < high) { int middle = (low + high) / 2; if (number < array[middle]) { return binarySearch(array, low, middle, number); } else if (number > array[middle]) { return binarySearch(array, middle+1, high, number); } else { return middle; // real result } } return -1; // element not found }
  • 27. Combinatorial Computing different situations Three main divisions: permutations combinations variations
  • 28. Combinatorial (2) Permutations – all sequences without repetitive digits Variations – all sequences consisting of all digits in the range Combinations – all sequences with no reversal (1, 2) or (2,1) but not both
  • 29. Permutation For a given number n create n-dimensional array with ordered permutations Create an array with digits 1 to n Permutations are n!
  • 30. Permutations (2) Pseudo code for i=n to 0: if a[i] > a[i-1]: for j=i to n: find min(a[j]) > a[i-1]; swap(a[i-1], a[j]); sort(a[i], n);
  • 32. Summary Algorithm is a step list that solves a problem Arrays could be placeholders for data We could sort arrays in different ways and search with different complexity Sequences could be arranged in different combinations
  • 33. Exercises Write a program that allocates array of 20 integers and initializes each element by its index multiplied by 5. Print the obtained array on the console. Write a program that reads two arrays from the console and compares them for equality. Write a program that compares two char arrays lexicographically (letter by letter). Write a program that finds the maximal increasing sequence of equal elements in an array. Example: {3, 2, 3, 4 , 2, 2, 4}  {2, 3, 4}.
  • 34. Exercises Write a program that reads two integer numbers N and K and an array of N elements from the console. Find in the array those K elements that have maximal sum. Sorting an array means to arrange its elements in increasing order. Write a program to sort an array. Use the &quot;selection sort&quot; algorithm: Find the smallest element, move it at the first position, find the smallest from the rest, move it at second position, etc.
  • 35. Exercises (6) * Write a program that sorts an int array using the quick sort algorithm. Write a program that creates an array containing all letters from the alphabet. Read a word from the console and print the index of each letter in the array. * Write a program that finds the index of given element in a sorted int array by using the binary search algorithm. * Write a program that sorts an int array using the merge sort algorithm.
  • 36. Homework Write a program that finds all prime numbers in the range [1...10 000 000]. Use the sieve of Eratosthenes algorithm. Write a program that reads two numbers n and k and generates all the variations of k elements from the set [ 1 .. n ]. Example: n = 3, k = 2  {1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3} Write a program that reads a number n and generates all the permutations of the numbers 1..n. Example: n = 3  {1, 2, 3}, {1, 3, 2}, {2, 1, 3}, {2, 3, 1}, {3, 1, 2}, {3, 2, 1}
  • 37. Homework (2) Write a program that fills and prints a matrix (n, n) as shown below: (examples for n = 4) a) b) c) d) 1 5 9 13 2 6 10 14 3 7 11 15 4 8 12 16 7 11 14 16 4 8 12 15 2 5 9 13 1 3 6 10 1 8 9 16 2 7 10 15 3 6 11 14 4 5 12 13 1 12 11 10 2 13 16 9 3 14 15 8 4 5 6 7
  • 38. Homework (3) * Write a program that finds the largest area of equal neighbor elements in a rectangular matrix and prints its size. Example: Hint: you can use the algorithm &quot; Depth-first search &quot; or &quot; Breadth-first search &quot;. 13 1 3 2 2 2 4 3 3 3 2 4 4 4 3 1 2 3 3 4 3 1 3 3 1 4 3 3 3 1 1

Editor's Notes

  • #2: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #3: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #4: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #5: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #6: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #7: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #8: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #9: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #10: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #11: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #12: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #13: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #14: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #15: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #16: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #17: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #18: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #19: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #20: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #21: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #22: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #23: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #24: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #25: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #26: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #27: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #28: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #29: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #30: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #31: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #32: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #33: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #34: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #35: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #36: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #37: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #38: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.
  • #39: (c) 2005 National Academy for Software Development - http://academy.devbg.org. All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.