SlideShare a Scribd company logo
1 of 20
PROGRAMMING IN C#
BASIC SORTING
ALGORITHMS
ENGR. MICHEAL OGUNDERO
YOU CAN CONTACT ME VIA
PHONE - +2348087365099
SKYPE – MICHEAL OGUNDERO
Email – ogunderoayodeji@gmail.com
CONTENT 2
1
2
3
4
INTRODUCTION
BIG-O NOTATION
BUBBLE SORT
5
6
7
8SELECTION SORT
INSERTION SORT
CODES ON GITHUB
A QUICK ONE! 3
• Write a program that takes a 2-digit integer input from a user.
• The program extracts the two digits from the user input.
• It stores the tens digit in a variable tensDigit and the unit digit in a
variable unitDigit
• It prints tensDigit and unitDigit to the console.
• Also swap the values of the tensDigit and unitDigit
• Print to the console again the current tensDigit and unitDigit
RESULTS
companyname.com
4
INTRODUCTION 5
• The two most common operations performed on data stored in a
computer are sorting and searching.
• Most of the data we work with in our day-to-day lives is sorted. For
example, we find definitions in a dictionary by searching alphabetically.
INTRODUCTION 6
• As was mentioned earlier, there has been quite a bit of research performed on
different sorting techniques. Although some very sophisticated sorting
algorithms have been developed.
• There are also several simple sorting algorithms you should study first.
• These sorting algorithms are the sort the bubble sort, selection sort and the
insertion sort. Each of these algorithms is easy to understand and easy to
implement.
• They are not the best overall algorithms for sorting by any means, but for small
data sets and in other special circumstances, they are the best algorithms to use.
BIG-O NOTATION 7
• Mathematical logic is the core of all programming. Most of its methods and
concepts are entirely based on what you learned in math class.
• If a computer program is like a meal with several ingredients,
the algorithm is the recipe. It shows you the ingredients (or “inputs”) and
all the steps it will take (or the “procedure”) to put your meal (or “output”)
together.
• Big-O notation is a mathematical function used to describe how complex
an algorithm is — or more specifically, the execution time required by an
algorithm.
• It does this by presenting a “worst-case” scenario of how long it would take
an algorithm to run (or in math terms, it puts an “asymptotic upper bound”
on the time it takes an algorithm to run).
BIG-O NOTATION…. 8
• O(1) describes an algorithm that will always execute in the same
time (or space) regardless of the size of the input data set.
• O(N) describes an algorithm whose performance will grow linearly
and in direct proportion to the size of the input data set
• O(N2) represents an algorithm whose performance is directly
proportional to the square of the size of the input data set.
• O(2N) denotes an algorithm whose growth doubles with each
addition to the input data set.
BUBBLE SORT 9
The bubble sort is one of the slowest sorting algorithms available, but it is also one
of the simplest sorts to understand and implement.
Assuming you are sorting a list of numbers in ascending order, higher values float
to the right whereas lower values float to the left.
This behavior is caused by moving through the list many times, comparing
adjacent values and swapping them if the value to the left is greater than the
value to the right.
Iteration 1: – 8 5 7 3 1 → 5 8 7 3 1 → 5 7 8 3 1 → 5 7 3 8 1→ 5 7 3 1 8
Iteration 2: – 5 7 3 1 8 → 5 3 7 1 8→ 5 3 1 7 8
Iteration 3: – 5 3 1 7 8 → 3 5 1 7 8 → 3 1 5 7 8
Iteration 4: – 3 1 5 7 8 → 1 3 5 7 8
Iteration 5: – 1 3 5 7 8
BUBBLE SORT IMPLEMENTATION 10
public void BubbleSort() {
int temp;
for(int outer = upper; outer >= 1; outer--) {
for(int inner = 0; inner <= outer-1;inner++) {
if ((int)arr[inner] > arr[inner+1]) {
temp = arr[inner];
arr[inner] = arr[inner+1];
arr[inner+1] = temp;
}
}
this.DisplayElements();
}
}
BUBBLE SORT… 11
In fact, this algorithm is never used in practice but is of historical interest. Like the
brute-force style of searching, it does way too much work to come up with the right
answer!
Time Complexity
Since we need to iterate the entire array for every element, the average and the
worst case complexity of bubble sort is O(n²).
SELECTION SORT 12
This algorithm follows the concept of dividing the given array into two subarrays.
• The subarray of sorted elements
• The subarray of unsorted elements
This sort works by starting at the beginning of the array, comparing the first element
with the other elements
in the array.
The smallest element is placed in position 0, and the sort then
begins again at position 1. This continues until each position except the last
position has been the starting point for a new loop.
SELECTION SORT 13
Two loops are used in the Selection Sort algorithm.
• The outer loop moves from the first element in the array to the next to last
element, whereas
• the inner loop moves from the second element of the array to the last element,
looking for values that are smaller than the element currently being pointed at by
the outer loop.
• After each iteration of the inner loop, the most minimum value in the array is
assigned to its proper place in the array.
SELECTION SORT IMPLEMENTATION 14
public void SelectionSort() {
int min, temp;
for(int outer = 0; outer <= upper; outer++) {
min = outer;
for(int inner = outer + 1; inner <= upper; inner++)
if (arr[inner] < arr[min])
min = inner;
temp = arr[outer];
arr[outer] = arr[min];
arr[min] = temp;
}
}
SELECTION SORT IMPLEMENTATION 15
Every element needs to be compared to every other element and then get swapped
to its correct position. After every iteration, the size of unsorted array reduces by 1.
Hence n swaps and (n*(n-1))/2 comparisons result in the complexity of Selection
Sort as O(n²).
Let us take an input array as – 8 5 7 3 1
The sorted output for this array is – 1 3 5 7 8
At nth iteration, elements from position 0 to n-1 will be sorted.
INSERTION SORT 16
• Here, a sub-list is maintained which is always sorted.
• For example, the lower part of an array is maintained to be sorted. An element
which is to be inserted in this sorted sub-list, has to find its appropriate place and
then it has to be inserted there.
• This algorithm is efficient for smaller datasets.
• The array is searched sequentially and unsorted items are moved and inserted
into the sorted sub-list (in the same array).
INSERTION SORT IMPLEMENTATION 17
The Insertion sort has two loops.
• The outer loop moves element by element through the array whereas the inner
loop compares the element chosen in the outer loop to the element next to it in
the array.
• If the element selected by the outer loop is less than the element selected by the
inner loop, array elements are shifted over to the right to make room for the
inner loop element, just as described in the preceding example.
INSERTION SORT IMPLEMENTATION 18
public void InsertionSort() {
int inner, temp;
for(int outer = 1; outer <= upper; outer++) {
temp = arr[outer];
inner = outer;
while(inner > 0 && arr[inner-1] >= temp) {
arr[inner] = arr[inner-1];
inner -= 1;
}
arr[inner] = temp;
}
}
CODES 19
Kindly visit my github page for the code
https://github.com/EngrMikolo/BasicSortingAlgorithms
• You can also fork the repo to extend the code
Systems Engineering Department,
University of Lagos, Nigeria.
(234) 808-736-5099 Micheal Ogundero
Thank You

More Related Content

What's hot

Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IMohamed Loey
 
3.2 insertion sort
3.2 insertion sort3.2 insertion sort
3.2 insertion sortKrish_ver2
 
04 brute force
04 brute force04 brute force
04 brute forceHira Gul
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort AlgorithmLemia Algmri
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhithRj Juhith
 
Selection sort
Selection sortSelection sort
Selection sortstella D
 
Selection sort 1
Selection sort 1Selection sort 1
Selection sort 1asmhemu
 
Selection Sort - Vipin Ramola
Selection Sort - Vipin RamolaSelection Sort - Vipin Ramola
Selection Sort - Vipin RamolaDipayan Sarkar
 
Data Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxData Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxEllenGrace9
 
Mathematical Analysis of Non-Recursive Algorithm.
Mathematical Analysis of Non-Recursive Algorithm.Mathematical Analysis of Non-Recursive Algorithm.
Mathematical Analysis of Non-Recursive Algorithm.mohanrathod18
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsMohamed Loey
 
Set data structure
Set data structure Set data structure
Set data structure Tech_MX
 

What's hot (20)

Algorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms IAlgorithms Lecture 4: Sorting Algorithms I
Algorithms Lecture 4: Sorting Algorithms I
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
3.2 insertion sort
3.2 insertion sort3.2 insertion sort
3.2 insertion sort
 
Quick sort
Quick sortQuick sort
Quick sort
 
04 brute force
04 brute force04 brute force
04 brute force
 
Quick sort
Quick sortQuick sort
Quick sort
 
heap Sort Algorithm
heap  Sort Algorithmheap  Sort Algorithm
heap Sort Algorithm
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Insertion sort
Insertion sort Insertion sort
Insertion sort
 
Selection sort
Selection sortSelection sort
Selection sort
 
Merge Sort
Merge SortMerge Sort
Merge Sort
 
Selection sort 1
Selection sort 1Selection sort 1
Selection sort 1
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Selection Sort - Vipin Ramola
Selection Sort - Vipin RamolaSelection Sort - Vipin Ramola
Selection Sort - Vipin Ramola
 
Data Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptxData Structures and Algorithm - Module 1.pptx
Data Structures and Algorithm - Module 1.pptx
 
Mathematical Analysis of Non-Recursive Algorithm.
Mathematical Analysis of Non-Recursive Algorithm.Mathematical Analysis of Non-Recursive Algorithm.
Mathematical Analysis of Non-Recursive Algorithm.
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching Algorithms
 
Data structures using C
Data structures using CData structures using C
Data structures using C
 
Set data structure
Set data structure Set data structure
Set data structure
 
Time andspacecomplexity
Time andspacecomplexityTime andspacecomplexity
Time andspacecomplexity
 

Similar to Basic Sorting algorithms csharp

Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
Time and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptxTime and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptxdudelover
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arraysmaamir farooq
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisRadhika Talaviya
 
lecture-k-sorting.ppt
lecture-k-sorting.pptlecture-k-sorting.ppt
lecture-k-sorting.pptSushantRaj25
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.pptLegesseSamuel
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdfharamaya university
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure Eman magdy
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printAbdii Rashid
 
Data Structures in C
Data Structures in CData Structures in C
Data Structures in CJabs6
 

Similar to Basic Sorting algorithms csharp (20)

Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Time and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptxTime and Space Complexity Analysis.pptx
Time and Space Complexity Analysis.pptx
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Sorting
SortingSorting
Sorting
 
Sorting
SortingSorting
Sorting
 
Data Structure (MC501)
Data Structure (MC501)Data Structure (MC501)
Data Structure (MC501)
 
Analysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysisAnalysis and Design of Algorithms -Sorting Algorithms and analysis
Analysis and Design of Algorithms -Sorting Algorithms and analysis
 
lecture-k-sorting.ppt
lecture-k-sorting.pptlecture-k-sorting.ppt
lecture-k-sorting.ppt
 
3.ppt
3.ppt3.ppt
3.ppt
 
Lecture k-sorting
Lecture k-sortingLecture k-sorting
Lecture k-sorting
 
daa unit 1.pptx
daa unit 1.pptxdaa unit 1.pptx
daa unit 1.pptx
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
 
16-sorting.ppt
16-sorting.ppt16-sorting.ppt
16-sorting.ppt
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
Sorting
SortingSorting
Sorting
 
Basics in algorithms and data structure
Basics in algorithms and data structure Basics in algorithms and data structure
Basics in algorithms and data structure
 
Chapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for printChapter 8 advanced sorting and hashing for print
Chapter 8 advanced sorting and hashing for print
 
Data Structures in C
Data Structures in CData Structures in C
Data Structures in C
 
simple-sorting algorithms
simple-sorting algorithmssimple-sorting algorithms
simple-sorting algorithms
 

More from Micheal Ogundero

csharp repitition structures
csharp repitition structurescsharp repitition structures
csharp repitition structuresMicheal Ogundero
 
escape sequences and substitution markers
escape sequences and substitution markersescape sequences and substitution markers
escape sequences and substitution markersMicheal Ogundero
 
A simple program C# program
A simple program C# programA simple program C# program
A simple program C# programMicheal Ogundero
 
datatypes_variables_constants
datatypes_variables_constantsdatatypes_variables_constants
datatypes_variables_constantsMicheal Ogundero
 
2 robot types_classifications
2 robot types_classifications2 robot types_classifications
2 robot types_classificationsMicheal Ogundero
 
c# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventionsc# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming ConventionsMicheal Ogundero
 
Dictionary and sets-converted
Dictionary and sets-convertedDictionary and sets-converted
Dictionary and sets-convertedMicheal Ogundero
 
csharp_Passing_parameters_by_value_and_reference
csharp_Passing_parameters_by_value_and_referencecsharp_Passing_parameters_by_value_and_reference
csharp_Passing_parameters_by_value_and_referenceMicheal Ogundero
 
C# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesC# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesMicheal Ogundero
 

More from Micheal Ogundero (15)

static methods
static methodsstatic methods
static methods
 
csharp repitition structures
csharp repitition structurescsharp repitition structures
csharp repitition structures
 
selection structures
selection structuresselection structures
selection structures
 
escape sequences and substitution markers
escape sequences and substitution markersescape sequences and substitution markers
escape sequences and substitution markers
 
A simple program C# program
A simple program C# programA simple program C# program
A simple program C# program
 
c# operators
c# operatorsc# operators
c# operators
 
datatypes_variables_constants
datatypes_variables_constantsdatatypes_variables_constants
datatypes_variables_constants
 
2 robot types_classifications
2 robot types_classifications2 robot types_classifications
2 robot types_classifications
 
History of robots
History of robotsHistory of robots
History of robots
 
c# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventionsc# keywords, identifiers and Naming Conventions
c# keywords, identifiers and Naming Conventions
 
Dictionary and sets-converted
Dictionary and sets-convertedDictionary and sets-converted
Dictionary and sets-converted
 
Csharp_List
Csharp_ListCsharp_List
Csharp_List
 
c# Enumerations
c# Enumerationsc# Enumerations
c# Enumerations
 
csharp_Passing_parameters_by_value_and_reference
csharp_Passing_parameters_by_value_and_referencecsharp_Passing_parameters_by_value_and_reference
csharp_Passing_parameters_by_value_and_reference
 
C# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data TypesC# Value Data Types and Reference Data Types
C# Value Data Types and Reference Data Types
 

Recently uploaded

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Recently uploaded (20)

Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

Basic Sorting algorithms csharp

  • 1. PROGRAMMING IN C# BASIC SORTING ALGORITHMS ENGR. MICHEAL OGUNDERO YOU CAN CONTACT ME VIA PHONE - +2348087365099 SKYPE – MICHEAL OGUNDERO Email – ogunderoayodeji@gmail.com
  • 2. CONTENT 2 1 2 3 4 INTRODUCTION BIG-O NOTATION BUBBLE SORT 5 6 7 8SELECTION SORT INSERTION SORT CODES ON GITHUB
  • 3. A QUICK ONE! 3 • Write a program that takes a 2-digit integer input from a user. • The program extracts the two digits from the user input. • It stores the tens digit in a variable tensDigit and the unit digit in a variable unitDigit • It prints tensDigit and unitDigit to the console. • Also swap the values of the tensDigit and unitDigit • Print to the console again the current tensDigit and unitDigit
  • 5. INTRODUCTION 5 • The two most common operations performed on data stored in a computer are sorting and searching. • Most of the data we work with in our day-to-day lives is sorted. For example, we find definitions in a dictionary by searching alphabetically.
  • 6. INTRODUCTION 6 • As was mentioned earlier, there has been quite a bit of research performed on different sorting techniques. Although some very sophisticated sorting algorithms have been developed. • There are also several simple sorting algorithms you should study first. • These sorting algorithms are the sort the bubble sort, selection sort and the insertion sort. Each of these algorithms is easy to understand and easy to implement. • They are not the best overall algorithms for sorting by any means, but for small data sets and in other special circumstances, they are the best algorithms to use.
  • 7. BIG-O NOTATION 7 • Mathematical logic is the core of all programming. Most of its methods and concepts are entirely based on what you learned in math class. • If a computer program is like a meal with several ingredients, the algorithm is the recipe. It shows you the ingredients (or “inputs”) and all the steps it will take (or the “procedure”) to put your meal (or “output”) together. • Big-O notation is a mathematical function used to describe how complex an algorithm is — or more specifically, the execution time required by an algorithm. • It does this by presenting a “worst-case” scenario of how long it would take an algorithm to run (or in math terms, it puts an “asymptotic upper bound” on the time it takes an algorithm to run).
  • 8. BIG-O NOTATION…. 8 • O(1) describes an algorithm that will always execute in the same time (or space) regardless of the size of the input data set. • O(N) describes an algorithm whose performance will grow linearly and in direct proportion to the size of the input data set • O(N2) represents an algorithm whose performance is directly proportional to the square of the size of the input data set. • O(2N) denotes an algorithm whose growth doubles with each addition to the input data set.
  • 9. BUBBLE SORT 9 The bubble sort is one of the slowest sorting algorithms available, but it is also one of the simplest sorts to understand and implement. Assuming you are sorting a list of numbers in ascending order, higher values float to the right whereas lower values float to the left. This behavior is caused by moving through the list many times, comparing adjacent values and swapping them if the value to the left is greater than the value to the right. Iteration 1: – 8 5 7 3 1 → 5 8 7 3 1 → 5 7 8 3 1 → 5 7 3 8 1→ 5 7 3 1 8 Iteration 2: – 5 7 3 1 8 → 5 3 7 1 8→ 5 3 1 7 8 Iteration 3: – 5 3 1 7 8 → 3 5 1 7 8 → 3 1 5 7 8 Iteration 4: – 3 1 5 7 8 → 1 3 5 7 8 Iteration 5: – 1 3 5 7 8
  • 10. BUBBLE SORT IMPLEMENTATION 10 public void BubbleSort() { int temp; for(int outer = upper; outer >= 1; outer--) { for(int inner = 0; inner <= outer-1;inner++) { if ((int)arr[inner] > arr[inner+1]) { temp = arr[inner]; arr[inner] = arr[inner+1]; arr[inner+1] = temp; } } this.DisplayElements(); } }
  • 11. BUBBLE SORT… 11 In fact, this algorithm is never used in practice but is of historical interest. Like the brute-force style of searching, it does way too much work to come up with the right answer! Time Complexity Since we need to iterate the entire array for every element, the average and the worst case complexity of bubble sort is O(n²).
  • 12. SELECTION SORT 12 This algorithm follows the concept of dividing the given array into two subarrays. • The subarray of sorted elements • The subarray of unsorted elements This sort works by starting at the beginning of the array, comparing the first element with the other elements in the array. The smallest element is placed in position 0, and the sort then begins again at position 1. This continues until each position except the last position has been the starting point for a new loop.
  • 13. SELECTION SORT 13 Two loops are used in the Selection Sort algorithm. • The outer loop moves from the first element in the array to the next to last element, whereas • the inner loop moves from the second element of the array to the last element, looking for values that are smaller than the element currently being pointed at by the outer loop. • After each iteration of the inner loop, the most minimum value in the array is assigned to its proper place in the array.
  • 14. SELECTION SORT IMPLEMENTATION 14 public void SelectionSort() { int min, temp; for(int outer = 0; outer <= upper; outer++) { min = outer; for(int inner = outer + 1; inner <= upper; inner++) if (arr[inner] < arr[min]) min = inner; temp = arr[outer]; arr[outer] = arr[min]; arr[min] = temp; } }
  • 15. SELECTION SORT IMPLEMENTATION 15 Every element needs to be compared to every other element and then get swapped to its correct position. After every iteration, the size of unsorted array reduces by 1. Hence n swaps and (n*(n-1))/2 comparisons result in the complexity of Selection Sort as O(n²). Let us take an input array as – 8 5 7 3 1 The sorted output for this array is – 1 3 5 7 8 At nth iteration, elements from position 0 to n-1 will be sorted.
  • 16. INSERTION SORT 16 • Here, a sub-list is maintained which is always sorted. • For example, the lower part of an array is maintained to be sorted. An element which is to be inserted in this sorted sub-list, has to find its appropriate place and then it has to be inserted there. • This algorithm is efficient for smaller datasets. • The array is searched sequentially and unsorted items are moved and inserted into the sorted sub-list (in the same array).
  • 17. INSERTION SORT IMPLEMENTATION 17 The Insertion sort has two loops. • The outer loop moves element by element through the array whereas the inner loop compares the element chosen in the outer loop to the element next to it in the array. • If the element selected by the outer loop is less than the element selected by the inner loop, array elements are shifted over to the right to make room for the inner loop element, just as described in the preceding example.
  • 18. INSERTION SORT IMPLEMENTATION 18 public void InsertionSort() { int inner, temp; for(int outer = 1; outer <= upper; outer++) { temp = arr[outer]; inner = outer; while(inner > 0 && arr[inner-1] >= temp) { arr[inner] = arr[inner-1]; inner -= 1; } arr[inner] = temp; } }
  • 19. CODES 19 Kindly visit my github page for the code https://github.com/EngrMikolo/BasicSortingAlgorithms • You can also fork the repo to extend the code
  • 20. Systems Engineering Department, University of Lagos, Nigeria. (234) 808-736-5099 Micheal Ogundero Thank You

Editor's Notes

  1. Image source:- https://pixabay.com/en/technology-industry-big-data-cpu-3092486/
  2. Image source:- https://pixabay.com/en/coding-programming-working-macbook-924920/