SlideShare a Scribd company logo
1 of 12
Download to read offline
http://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm Copyright © tutorialspoint.com
DATA STRUCTURE - BUBBLE SORT ALGORITHMDATA STRUCTURE - BUBBLE SORT ALGORITHM
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison based algorithm in
which each pair of adjacent elements is compared and elements are swapped if they are not in
order. This algorithm is not suitable for large data sets as its average and worst case complexity
are of O(n2) where n are no. of items.
How bubble sort works?
We take an unsorted array for our example. Bubble sort take Ο(n2) time so we're keeping short
and precise.
Bubble sort starts with very first two elements, comparing them to check which one is greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33
with 27.
We find that 27 is smaller than 33 and these two values must be swapped.
The new array should look like this −
Next we compare 33 and 35. We find that both are in already sorted positions.
Then we move to next two values, 35 and 10.
We know than 10 is smaller 35. Hence they are not sorted.
We swap these values. We find that we reach at the end of the array. After one iteration the array
should look like this −
To be precise, we are now showing that how array should look like after each iteration. After
second iteration, it should look like this −
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that array is completely sorted.
Now we should look into some practical aspects of bubble sort.
Algorithm
We assume list is an array of n elements. We further assume that swap function, swaps the values
of given array elements.
begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
Pseudocode
We observe in algorithm that Bubble Sort compares each pair of array element unless the whole
array is completely sorted ascending. This may cause few complexity issues like what if the array
needs no more swapping as all the elements are already ascending.
To ease-out the issue, we use one flag variable swapped which will help us to see if any swap is
happened or not. If no swap is occurred, i.e. the array requires no more processing to be sorted, it
will come out of the loop.
Pseudocode of BubbleSort algorithm can be written as given below −
procedure bubbleSort( list : array of items )
loop = list.count;
for i = 0 to loop-1 do:
swapped = false
for j = 0 to loop-1 do:
/* compare the adjacent elements */
if list[j] > list[j+1] then
/* swap them */
swap( list[j], list[j+1] )
swapped = true
end if
end for
/*if no number was swapped that means
array is sorted now, break the loop.*/
if(not swapped) then
break
end if
end for
end procedure return list
Implementation
One more issue we did not address in our original algorithm and its improvised pseudocode, that
is, after every iteration the highest values settles down at the end of the array. So next iteration
needs not to include already sorted elements. For this purpose, in our implementation, we restrict
the inner loop to avoid already sorted values.
To see bubble sort implementation in C programming language, please click here.
bubble.txt
/* Bubble sort code */
#include <iostream.h>
int main()
{
int array[100], n, c, d, swap;
cout<<"Enter number of elementsn";
cin>>n;
cout<<"Enter"<<n<<"integersn";
for (c = 0; c < n; c++)
cin>>array[c];
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
cout<<"Sorted list in ascending order:n";
for ( c = 0 ; c < n ; c++ )
cout<<"n"<< array[c];
return 0;
}
Page 1
http://www.tutorialspoint.com/data_structures_algorithms/insertion_sort_algorithm.htm
Copyright © tutorialspoint.com
DATA STRUCTURE - INSERTION SORTDATA STRUCTURE - INSERTION SORT
This is a in-place comparison based sorting algorithm. Here, a sub-list is maintained which is
always sorted. For example, the lower part of an array is maintained to be sorted. A element which
is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and insert it there. Hence
the name insertion sort.
The array is searched sequentially and unsorted items are moved and inserted into sorted sub-list
inthesamearray. This algorithm is not suitable for large data sets as its average and worst case
complexity are of Ο(n2) where n are no. of items.
How insertion sort works?
We take an unsorted array for our example.
Insertion sort compares the first two elements.
It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list.
Insertion sort moves ahead and compares 33 with 27.
And finds that 33 is not in correct position.
It swaps 33 with 27. Also it checks with all the elements of sorted sublist. Here we see that sorted
sub-list has only one element 14 and 27 is greater than 14. Hence sorted sub-list remain sorted
after swapping.
By now we have 14 and 27 in the sorted sublist. Next it compares 33 with 10,.
These values are not in sorted order.
So we swap them.
But swapping makes 27 and 10 unsorted.
So we swap them too.
Again we find 14 and 10 in unsorted order.
And we swap them. By the end of third iteration we have a sorted sublist of 3 items.
This process goes until all the unsorted values are covered in sorted sublist. And now we shall see
some programming aspects of insertion sort.
Algorithm
Now we have a bigger picture of how this sorting technique works, so we can derive simple steps
by which we can achieve insertion sort.
Step 1 − If it is the first element, it is already sorted. return 1;
Step 1 − Pick next element
Step 1 − Compare with all elements in the sorted sub-list
Step 1 − Find appropriate position
Step 1 − Insert the value
Step 1 − Repeat until list is sorted
Pseudocode
procedure insertionSort( A : array of items )
int holePosition
int valueToInsert
for i = 1 to length(A) inclusive do:
/* select value to be inserted */
valueToInsert = A[i]
holePosition = i
/*locate hole position for the element to be inserted */
while holePosition > 0 and A[i-1] > valueToInsert do:
A[holePosition] = A[holePosition-1]
holePosition = holePosition -1
end while
/* insert the number at hole position */
A[holePosition] = valueToInsert
end for
end procedure
To see insertion sort implementation in C programming language, please click here.
Loading [MathJax]/jax/output/HTML-CSS/jax.js
insertion.txt
/* insertion sort code */
#include <iostream.h>
int main()
{
int array[100], n, c, d, swap;
cout<<"Enter number of elementsn";
cin>>n;
cout<<"Enter"<<n<<"integersn";
for (c = 0; c < n; c++)
cin>>array[c];
for (c = 1 ; c <= n - 1; c++) {
d = c;
while ( d > 0 && array[d] < array[d-1]) {
t = array[d];
array[d] = array[d-1];
array[d-1] = t;
d--;
}
}
cout<<"Sorted list in ascending order:n";
for ( c = 0 ; c < n ; c++ )
cout<<"n"<< array[c];
return 0;
}
Page 1
http://www.tutorialspoint.com/data_structures_algorithms/selection_sort_algorithm.htm
Copyright © tutorialspoint.com
DATA STRUCTURE - SELECTION SORTDATA STRUCTURE - SELECTION SORT
Selection sort is a simple sorting algorithm. This sorting algorithm is a in-place comparison based
algorithm in which the list is divided into two parts, sorted part at left end and unsorted part at right
end. Initially sorted part is empty and unsorted part is entire list.
Smallest element is selected from the unsorted array and swapped with the leftmost element and
that element becomes part of sorted array. This process continues moving unsorted array
boundary by one element to the right.
This algorithm is not suitable for large data sets as its average and worst case complexity are of
O(n2) where n are no. of items.
How selection sort works?
We take the below depicted array for our example.
For the first position in the sorted list, the whole list is scanned sequentially. The first position
where 14 is stored presently, we search the whole list and find that 10 is the lowest value.
So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the
list, appears in the first position of sorted list.
For the second position, where 33 is residing, we start scanning the rest of the list in linear manner.
We find that 14 is the second lowest value in the list and it should appear at the second place. We
swap these values.
After two iterations, two least values are positioned at the the beginning in the sorted manner.
The same process is applied on the rest of the items in the array. We shall see an pictorial
depiction of entire sorting process −
Now, we should learn some programming aspects of selection sort.
Algorithm
Step 1 − Set MIN to location 0
Step 2 − Search the minimum element in the list
Step 3 − Swap with value at location MIN
Step 4 − Increment MIN to point to next element
Step 5 − Repeat until list is sorted
Pseudocode
procedure selection sort
list : array of items
n : size of list
for i = 1 to n - 1
/* set current element as minimum*/
min = i
/* check the element to be minimum */
for j = i+1 to n
if list[j] < list[min] then
min = j;
end if
end for
/* swap the minimum element with the current element*/
if indexMin != i then
swap list[min] and list[i]
end if
end for
end procedure
To see selection sort implementation in C programming language, please click here.
selection.txt
/* selection sort code */
#include <iostream.h>
int main()
{
int array[100], n, c, d, swap;
cout<<"Enter number of elementsn";
cin>>n;
cout<<"Enter"<<n<<"integersn";
for (c = 0; c < n; c++)
cin>>array[c];
for ( c = 0 ; c < ( n - 1 ) ; c++ )
{
position = c;
for ( d = c + 1 ; d < n ; d++ )
{
if ( array[position] > array[d] )
position = d;
}
if ( position != c )
{
swap = array[c];
array[c] = array[position];
array[position] = swap;
}
}
cout<<"Sorted list in ascending order:n";
for ( c = 0 ; c < n ; c++ )
cout<<"n"<< array[c];
return 0;
}
Page 1

More Related Content

What's hot

Bubble sort | Data structure |
Bubble sort | Data structure |Bubble sort | Data structure |
Bubble sort | Data structure |MdSaiful14
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsMohamed Loey
 
Binary search in data structure
Binary search in data structureBinary search in data structure
Binary search in data structureMeherul1234
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisSNJ Chaudhary
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting AlgorithmsRahul Jamwal
 
Unsupervised learning
Unsupervised learningUnsupervised learning
Unsupervised learningamalalhait
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsDrishti Bhalla
 
trees in data structure
trees in data structure trees in data structure
trees in data structure shameen khan
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureBalwant Gorad
 
Joins in databases
Joins in databases Joins in databases
Joins in databases CourseHunt
 
Data Structure and Algorithms Hashing
Data Structure and Algorithms HashingData Structure and Algorithms Hashing
Data Structure and Algorithms HashingManishPrajapati78
 
Dag representation of basic blocks
Dag representation of basic blocksDag representation of basic blocks
Dag representation of basic blocksJothi Lakshmi
 
Java Linked List Tutorial | Edureka
Java Linked List Tutorial |  EdurekaJava Linked List Tutorial |  Edureka
Java Linked List Tutorial | EdurekaEdureka!
 

What's hot (20)

Bubble sort | Data structure |
Bubble sort | Data structure |Bubble sort | Data structure |
Bubble sort | Data structure |
 
Algorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to AlgorithmsAlgorithms Lecture 1: Introduction to Algorithms
Algorithms Lecture 1: Introduction to Algorithms
 
Binary search in data structure
Binary search in data structureBinary search in data structure
Binary search in data structure
 
Quick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And AnalysisQuick sort Algorithm Discussion And Analysis
Quick sort Algorithm Discussion And Analysis
 
Unit 1 dsa
Unit 1 dsaUnit 1 dsa
Unit 1 dsa
 
Analysis of the source program
Analysis of the source programAnalysis of the source program
Analysis of the source program
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
Unsupervised learning
Unsupervised learningUnsupervised learning
Unsupervised learning
 
Recognition-of-tokens
Recognition-of-tokensRecognition-of-tokens
Recognition-of-tokens
 
Binary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of AlgorithmsBinary Search - Design & Analysis of Algorithms
Binary Search - Design & Analysis of Algorithms
 
Algorithm Design and Analysis
Algorithm Design and AnalysisAlgorithm Design and Analysis
Algorithm Design and Analysis
 
Insertion sort
Insertion sort Insertion sort
Insertion sort
 
Distributed DBMS - Unit 6 - Query Processing
Distributed DBMS - Unit 6 - Query ProcessingDistributed DBMS - Unit 6 - Query Processing
Distributed DBMS - Unit 6 - Query Processing
 
trees in data structure
trees in data structure trees in data structure
trees in data structure
 
Prime number generation
Prime number generationPrime number generation
Prime number generation
 
Searching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data StructureSearching and Sorting Techniques in Data Structure
Searching and Sorting Techniques in Data Structure
 
Joins in databases
Joins in databases Joins in databases
Joins in databases
 
Data Structure and Algorithms Hashing
Data Structure and Algorithms HashingData Structure and Algorithms Hashing
Data Structure and Algorithms Hashing
 
Dag representation of basic blocks
Dag representation of basic blocksDag representation of basic blocks
Dag representation of basic blocks
 
Java Linked List Tutorial | Edureka
Java Linked List Tutorial |  EdurekaJava Linked List Tutorial |  Edureka
Java Linked List Tutorial | Edureka
 

Viewers also liked

Bubblesort Algorithm
Bubblesort AlgorithmBubblesort Algorithm
Bubblesort AlgorithmTobias Straub
 
Bubble sort a best presentation topic
Bubble sort a best presentation topicBubble sort a best presentation topic
Bubble sort a best presentation topicSaddam Hussain
 
Bubble Sort
Bubble SortBubble Sort
Bubble Sortgeeortiz
 
Bubble sort
Bubble sortBubble sort
Bubble sortManek Ar
 
Intersection Study - Algorithm(Sort)
Intersection Study - Algorithm(Sort)Intersection Study - Algorithm(Sort)
Intersection Study - Algorithm(Sort)Jea Hyeun Jung
 
3.1 bubble sort
3.1 bubble sort3.1 bubble sort
3.1 bubble sortKrish_ver2
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sortingKaushal Shah
 
Algorithm analysis (All in one)
Algorithm analysis (All in one)Algorithm analysis (All in one)
Algorithm analysis (All in one)jehan1987
 
Chemistry - Chp 4 - Atomic Structure - PowerPoint
Chemistry - Chp 4 - Atomic Structure - PowerPointChemistry - Chp 4 - Atomic Structure - PowerPoint
Chemistry - Chp 4 - Atomic Structure - PowerPointMr. Walajtys
 
time-management-ppt
time-management-ppttime-management-ppt
time-management-pptAgrima
 

Viewers also liked (15)

Bubblesort Algorithm
Bubblesort AlgorithmBubblesort Algorithm
Bubblesort Algorithm
 
Bubble sort a best presentation topic
Bubble sort a best presentation topicBubble sort a best presentation topic
Bubble sort a best presentation topic
 
Bubble Sort
Bubble SortBubble Sort
Bubble Sort
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Python Day1
Python Day1Python Day1
Python Day1
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Intersection Study - Algorithm(Sort)
Intersection Study - Algorithm(Sort)Intersection Study - Algorithm(Sort)
Intersection Study - Algorithm(Sort)
 
Bubble sort algorithm
Bubble sort algorithmBubble sort algorithm
Bubble sort algorithm
 
3.1 bubble sort
3.1 bubble sort3.1 bubble sort
3.1 bubble sort
 
Sorting
SortingSorting
Sorting
 
Data Structures - Searching & sorting
Data Structures - Searching & sortingData Structures - Searching & sorting
Data Structures - Searching & sorting
 
Algorithm analysis (All in one)
Algorithm analysis (All in one)Algorithm analysis (All in one)
Algorithm analysis (All in one)
 
String
StringString
String
 
Chemistry - Chp 4 - Atomic Structure - PowerPoint
Chemistry - Chp 4 - Atomic Structure - PowerPointChemistry - Chp 4 - Atomic Structure - PowerPoint
Chemistry - Chp 4 - Atomic Structure - PowerPoint
 
time-management-ppt
time-management-ppttime-management-ppt
time-management-ppt
 

Similar to Sorting

Similar to Sorting (20)

Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Sorting
SortingSorting
Sorting
 
Heap, quick and merge sort
Heap, quick and merge sortHeap, quick and merge sort
Heap, quick and merge sort
 
Selection sort
Selection sortSelection sort
Selection sort
 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
my docoment
my docomentmy docoment
my docoment
 
Sorting
SortingSorting
Sorting
 
Dsa – data structure and algorithms sorting
Dsa – data structure and algorithms  sortingDsa – data structure and algorithms  sorting
Dsa – data structure and algorithms sorting
 
Merge radix-sort-algorithm
Merge radix-sort-algorithmMerge radix-sort-algorithm
Merge radix-sort-algorithm
 
Merge radix-sort-algorithm
Merge radix-sort-algorithmMerge radix-sort-algorithm
Merge radix-sort-algorithm
 
Bubble sorting lab manual
Bubble sorting lab manualBubble sorting lab manual
Bubble sorting lab manual
 
Unit v data structure-converted
Unit  v data structure-convertedUnit  v data structure-converted
Unit v data structure-converted
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
An Experiment to Determine and Compare Practical Efficiency of Insertion Sort...
 
Ada notes
Ada notesAda notes
Ada notes
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 

Recently uploaded

Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonApplitools
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shardsChristopher Curtin
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesKrzysztofKkol1
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxRTS corp
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 

Recently uploaded (20)

Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + KobitonLeveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
Leveraging AI for Mobile App Testing on Real Devices | Applitools + Kobiton
 
2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards2024 DevNexus Patterns for Resiliency: Shuffle shards
2024 DevNexus Patterns for Resiliency: Shuffle shards
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilitiesAmazon Bedrock in Action - presentation of the Bedrock's capabilities
Amazon Bedrock in Action - presentation of the Bedrock's capabilities
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptx
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 

Sorting

  • 1. http://www.tutorialspoint.com/data_structures_algorithms/bubble_sort_algorithm.htm Copyright © tutorialspoint.com DATA STRUCTURE - BUBBLE SORT ALGORITHMDATA STRUCTURE - BUBBLE SORT ALGORITHM Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison based algorithm in which each pair of adjacent elements is compared and elements are swapped if they are not in order. This algorithm is not suitable for large data sets as its average and worst case complexity are of O(n2) where n are no. of items. How bubble sort works? We take an unsorted array for our example. Bubble sort take Ο(n2) time so we're keeping short and precise. Bubble sort starts with very first two elements, comparing them to check which one is greater. In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33 with 27. We find that 27 is smaller than 33 and these two values must be swapped. The new array should look like this − Next we compare 33 and 35. We find that both are in already sorted positions. Then we move to next two values, 35 and 10. We know than 10 is smaller 35. Hence they are not sorted.
  • 2. We swap these values. We find that we reach at the end of the array. After one iteration the array should look like this − To be precise, we are now showing that how array should look like after each iteration. After second iteration, it should look like this − Notice that after each iteration, at least one value moves at the end. And when there's no swap required, bubble sorts learns that array is completely sorted. Now we should look into some practical aspects of bubble sort. Algorithm We assume list is an array of n elements. We further assume that swap function, swaps the values of given array elements. begin BubbleSort(list) for all elements of list if list[i] > list[i+1] swap(list[i], list[i+1]) end if end for return list end BubbleSort Pseudocode We observe in algorithm that Bubble Sort compares each pair of array element unless the whole array is completely sorted ascending. This may cause few complexity issues like what if the array needs no more swapping as all the elements are already ascending. To ease-out the issue, we use one flag variable swapped which will help us to see if any swap is happened or not. If no swap is occurred, i.e. the array requires no more processing to be sorted, it will come out of the loop. Pseudocode of BubbleSort algorithm can be written as given below − procedure bubbleSort( list : array of items ) loop = list.count; for i = 0 to loop-1 do: swapped = false for j = 0 to loop-1 do:
  • 3. /* compare the adjacent elements */ if list[j] > list[j+1] then /* swap them */ swap( list[j], list[j+1] ) swapped = true end if end for /*if no number was swapped that means array is sorted now, break the loop.*/ if(not swapped) then break end if end for end procedure return list Implementation One more issue we did not address in our original algorithm and its improvised pseudocode, that is, after every iteration the highest values settles down at the end of the array. So next iteration needs not to include already sorted elements. For this purpose, in our implementation, we restrict the inner loop to avoid already sorted values. To see bubble sort implementation in C programming language, please click here.
  • 4. bubble.txt /* Bubble sort code */ #include <iostream.h> int main() { int array[100], n, c, d, swap; cout<<"Enter number of elementsn"; cin>>n; cout<<"Enter"<<n<<"integersn"; for (c = 0; c < n; c++) cin>>array[c]; for (c = 0 ; c < ( n - 1 ); c++) { for (d = 0 ; d < n - c - 1; d++) { if (array[d] > array[d+1]) /* For decreasing order use < */ { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } } cout<<"Sorted list in ascending order:n"; for ( c = 0 ; c < n ; c++ ) cout<<"n"<< array[c]; return 0; } Page 1
  • 5. http://www.tutorialspoint.com/data_structures_algorithms/insertion_sort_algorithm.htm Copyright © tutorialspoint.com DATA STRUCTURE - INSERTION SORTDATA STRUCTURE - INSERTION SORT This is a in-place comparison based sorting algorithm. Here, a sub-list is maintained which is always sorted. For example, the lower part of an array is maintained to be sorted. A element which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and insert it there. Hence the name insertion sort. The array is searched sequentially and unsorted items are moved and inserted into sorted sub-list inthesamearray. This algorithm is not suitable for large data sets as its average and worst case complexity are of Ο(n2) where n are no. of items. How insertion sort works? We take an unsorted array for our example. Insertion sort compares the first two elements. It finds that both 14 and 33 are already in ascending order. For now, 14 is in sorted sub-list. Insertion sort moves ahead and compares 33 with 27. And finds that 33 is not in correct position. It swaps 33 with 27. Also it checks with all the elements of sorted sublist. Here we see that sorted sub-list has only one element 14 and 27 is greater than 14. Hence sorted sub-list remain sorted after swapping. By now we have 14 and 27 in the sorted sublist. Next it compares 33 with 10,. These values are not in sorted order.
  • 6. So we swap them. But swapping makes 27 and 10 unsorted. So we swap them too. Again we find 14 and 10 in unsorted order. And we swap them. By the end of third iteration we have a sorted sublist of 3 items. This process goes until all the unsorted values are covered in sorted sublist. And now we shall see some programming aspects of insertion sort. Algorithm Now we have a bigger picture of how this sorting technique works, so we can derive simple steps by which we can achieve insertion sort. Step 1 − If it is the first element, it is already sorted. return 1; Step 1 − Pick next element Step 1 − Compare with all elements in the sorted sub-list Step 1 − Find appropriate position Step 1 − Insert the value Step 1 − Repeat until list is sorted Pseudocode procedure insertionSort( A : array of items ) int holePosition int valueToInsert for i = 1 to length(A) inclusive do: /* select value to be inserted */ valueToInsert = A[i] holePosition = i /*locate hole position for the element to be inserted */ while holePosition > 0 and A[i-1] > valueToInsert do:
  • 7. A[holePosition] = A[holePosition-1] holePosition = holePosition -1 end while /* insert the number at hole position */ A[holePosition] = valueToInsert end for end procedure To see insertion sort implementation in C programming language, please click here. Loading [MathJax]/jax/output/HTML-CSS/jax.js
  • 8. insertion.txt /* insertion sort code */ #include <iostream.h> int main() { int array[100], n, c, d, swap; cout<<"Enter number of elementsn"; cin>>n; cout<<"Enter"<<n<<"integersn"; for (c = 0; c < n; c++) cin>>array[c]; for (c = 1 ; c <= n - 1; c++) { d = c; while ( d > 0 && array[d] < array[d-1]) { t = array[d]; array[d] = array[d-1]; array[d-1] = t; d--; } } cout<<"Sorted list in ascending order:n"; for ( c = 0 ; c < n ; c++ ) cout<<"n"<< array[c]; return 0; } Page 1
  • 9. http://www.tutorialspoint.com/data_structures_algorithms/selection_sort_algorithm.htm Copyright © tutorialspoint.com DATA STRUCTURE - SELECTION SORTDATA STRUCTURE - SELECTION SORT Selection sort is a simple sorting algorithm. This sorting algorithm is a in-place comparison based algorithm in which the list is divided into two parts, sorted part at left end and unsorted part at right end. Initially sorted part is empty and unsorted part is entire list. Smallest element is selected from the unsorted array and swapped with the leftmost element and that element becomes part of sorted array. This process continues moving unsorted array boundary by one element to the right. This algorithm is not suitable for large data sets as its average and worst case complexity are of O(n2) where n are no. of items. How selection sort works? We take the below depicted array for our example. For the first position in the sorted list, the whole list is scanned sequentially. The first position where 14 is stored presently, we search the whole list and find that 10 is the lowest value. So we replace 14 with 10. After one iteration 10, which happens to be the minimum value in the list, appears in the first position of sorted list. For the second position, where 33 is residing, we start scanning the rest of the list in linear manner. We find that 14 is the second lowest value in the list and it should appear at the second place. We swap these values. After two iterations, two least values are positioned at the the beginning in the sorted manner. The same process is applied on the rest of the items in the array. We shall see an pictorial depiction of entire sorting process −
  • 10. Now, we should learn some programming aspects of selection sort. Algorithm Step 1 − Set MIN to location 0 Step 2 − Search the minimum element in the list Step 3 − Swap with value at location MIN Step 4 − Increment MIN to point to next element Step 5 − Repeat until list is sorted Pseudocode procedure selection sort list : array of items n : size of list for i = 1 to n - 1 /* set current element as minimum*/ min = i /* check the element to be minimum */ for j = i+1 to n if list[j] < list[min] then min = j; end if
  • 11. end for /* swap the minimum element with the current element*/ if indexMin != i then swap list[min] and list[i] end if end for end procedure To see selection sort implementation in C programming language, please click here.
  • 12. selection.txt /* selection sort code */ #include <iostream.h> int main() { int array[100], n, c, d, swap; cout<<"Enter number of elementsn"; cin>>n; cout<<"Enter"<<n<<"integersn"; for (c = 0; c < n; c++) cin>>array[c]; for ( c = 0 ; c < ( n - 1 ) ; c++ ) { position = c; for ( d = c + 1 ; d < n ; d++ ) { if ( array[position] > array[d] ) position = d; } if ( position != c ) { swap = array[c]; array[c] = array[position]; array[position] = swap; } } cout<<"Sorted list in ascending order:n"; for ( c = 0 ; c < n ; c++ ) cout<<"n"<< array[c]; return 0; } Page 1