SlideShare ist ein Scribd-Unternehmen logo
1 von 12
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - NotesOmprakash Chauhan
 
GAC DS Priority Queue Presentation 2022.ppt
GAC DS Priority Queue Presentation 2022.pptGAC DS Priority Queue Presentation 2022.ppt
GAC DS Priority Queue Presentation 2022.pptCUO VEERANAN VEERANAN
 
Java presentation on insertion sort
Java presentation on insertion sortJava presentation on insertion sort
Java presentation on insertion sort_fahad_shaikh
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Balwant Gorad
 
Bubble sort
Bubble sortBubble sort
Bubble sortManek Ar
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked ListNinad Mankar
 
Skip list vinay khimsuriya_200430723005
Skip list vinay khimsuriya_200430723005Skip list vinay khimsuriya_200430723005
Skip list vinay khimsuriya_200430723005vinaykhimsuriya1
 
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
List Data Structure
List Data StructureList Data Structure
List Data StructureZidny Nafan
 
Types of keys in dbms
Types of keys in dbmsTypes of keys in dbms
Types of keys in dbmsdarshhingu
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applicationssomendra kumar
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked listKeval Bhogayata
 
Inheritance in Object Oriented Programming
Inheritance in Object Oriented ProgrammingInheritance in Object Oriented Programming
Inheritance in Object Oriented ProgrammingAshita Agrawal
 

Was ist angesagt? (20)

Merge Sort
Merge SortMerge Sort
Merge Sort
 
Queue - Data Structure - Notes
Queue - Data Structure - NotesQueue - Data Structure - Notes
Queue - Data Structure - Notes
 
GAC DS Priority Queue Presentation 2022.ppt
GAC DS Priority Queue Presentation 2022.pptGAC DS Priority Queue Presentation 2022.ppt
GAC DS Priority Queue Presentation 2022.ppt
 
Java presentation on insertion sort
Java presentation on insertion sortJava presentation on insertion sort
Java presentation on insertion sort
 
Quick sort
Quick sortQuick sort
Quick sort
 
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
Linked List, Types of Linked LIst, Various Operations, Applications of Linked...
 
Stacks in Data Structure
Stacks in Data StructureStacks in Data Structure
Stacks in Data Structure
 
Bubble sort
Bubble sortBubble sort
Bubble sort
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Linear data structure concepts
Linear data structure conceptsLinear data structure concepts
Linear data structure concepts
 
Skip list vinay khimsuriya_200430723005
Skip list vinay khimsuriya_200430723005Skip list vinay khimsuriya_200430723005
Skip list vinay khimsuriya_200430723005
 
stack presentation
stack presentationstack presentation
stack presentation
 
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil9. Searching & Sorting - Data Structures using C++ by Varsha Patil
9. Searching & Sorting - Data Structures using C++ by Varsha Patil
 
Queues
QueuesQueues
Queues
 
Queue Data Structure
Queue Data StructureQueue Data Structure
Queue Data Structure
 
List Data Structure
List Data StructureList Data Structure
List Data Structure
 
Types of keys in dbms
Types of keys in dbmsTypes of keys in dbms
Types of keys in dbms
 
queue & its applications
queue & its applicationsqueue & its applications
queue & its applications
 
Insertion in singly linked list
Insertion in singly linked listInsertion in singly linked list
Insertion in singly linked list
 
Inheritance in Object Oriented Programming
Inheritance in Object Oriented ProgrammingInheritance in Object Oriented Programming
Inheritance in Object Oriented Programming
 

Andere mochten auch

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
 
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
 

Andere mochten auch (14)

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
 
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
 

Ähnlich wie Sorting

Ähnlich wie 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
 

Kürzlich hochgeladen

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 

Kürzlich hochgeladen (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 

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