SlideShare ist ein Scribd-Unternehmen logo
1 von 18
Programming
Sorting
Arrays
MP102 Prog. Fundamentals. Sorting I/ Slide 2
Sorting
To arrange a set of items in sequence.
It is estimated that 25~50% of all
computing power is used for sorting
activities.
Possible reasons:
Many applications require sorting;
Many applications perform sorting when they
don't have to;
Many applications use inefficient sorting
algorithms.
MP102 Prog. Fundamentals. Sorting I/ Slide 3
Sorting Applications
To prepare a list of student ID, names, and
scores in a table (sorted by ID or name) for easy
checking.
To prepare a list of scores before letter grade
assignment.
To produce a list of horses after a race (sorted
by the finishing times) for payoff calculation.
To prepare an originally unsorted array for
ordered binary searching.
MP102 Prog. Fundamentals. Sorting I/ Slide 4
Some Sorting Methods
Selection sort
Bubble sort
Shell sort (a simple but faster sorting
method than above; see p.331 of
Numerical Recipes in C, 2nd ed., by
William H. Press et al, Cambridge
University Press, 1992)
Quick sort (a very efficient sorting method
for most applications; p.332-336, ibid.)
MP102 Prog. Fundamentals. Sorting I/ Slide 5
Ex. 1A: Selection Sort
Selection sort performs sorting by
repeatedly putting the largest element in
the unsorted portion of the array to the
end of this unsorted portion until the whole
array is sorted.
It is similar to the way that many people do
their sorting.
MP102 Prog. Fundamentals. Sorting I/ Slide 6
Ex. 1A: Selection Sort
Algorithm
1. Define the entire array as the unsorted
portion of the array
2. While the unsorted portion of the array
has more than one element:
⇒ Find its largest element.
⇒ Swap with last element (assuming their
values are different).
⇒ Reduce the size of the unsorted
portion of the array by 1.
Before sorting 14 2 10 5 1 3 17 7
After pass 1 14 2 10 5 1 3 7 17
After pass 2 7 2 10 5 1 3 14 17
After pass 3 7 2 3 5 1 10 14 17
After pass 4 1 2 3 5 7 10 14 17
// Sort array of integers in ascending order
void select(int data[], // in/output: array
int size){ // input: array size
int temp; // for swap
int max_index; // index of max value
for (int rightmost=size-1; rightmost>0; rightmost--){
//find the largest item in the unsorted portion
//rightmost is the end point of the unsorted part of array
max_index = 0; //points the largest element
for ( int current=1; current<=rightmost; current++)
if (data[current] > data[max_index])
max_index = current;
//swap the largest item with last item if necessary
if (data[max_index] > data[rightmost]){
temp = data[max_index]; // swap
data[max_index] = data[rightmost];
data[rightmost] = temp;
}
}}
const int array_size = 8;
int main() {
int list[array_size] = {14, 2, 10, 5, 1,
3, 17, 7};
int index, ans;
cout << "Before sorting: ";
for (index = 0; index<array_size; index++)
cout << list[index] <<" ";
cout << endl;
cout << "Enter sorting method 1(select), 2(bubble):";
cin >> ans;
if (ans == 1) select(list, array_size);
else bubble(list, array_size);
cout << endl << "After sorting: ";
for (index = 0; index<array_size; index++)
cout << list[index] <<" ";
cout << endl;
return 0;
}
P102 Prog. Fundamentals. Sorting I/ Slide 10
Ex. 1B: Bubble Sort
Bubble sort examines the array from start
to finish, comparing elements as it goes.
Any time it finds a larger element before a smaller
element, it swaps the two.
In this way, the larger elements are passed
towards the end.
The largest element of the array therefore
"bubbles" to the end of the array.
Then it repeats the process for the unsorted
portion of the array until the whole array is sorted.
P102 Prog. Fundamentals. Sorting I/ Slide 11
Ex. 1A: Bubble Sort
Bubble sort works on the same general principle as
shaking a soft drink bottle.
Right after shaking, the contents are a mixture of
bubbles and soft drink, distributed randomly.
Because bubbles are lighter than the soft drink,
they rise to the surface, displacing the soft drink
downwards.
This is how bubble sort got its name, because the
smaller elements "float" to the top, while
the larger elements "sink" to the bottom.
P102 Prog. Fundamentals. Sorting I/ Slide 12
Ex. 1B: Bubble Sort
Algorithm
Define the entire array as the unsorted
portion of the array.
While the unsorted portion of the array
has more than one element:
1. For every element in the unsorted portion,
swap with the next neighbor if it is larger than
the neighbor.
2. Reduce the size of the unsorted portion of the
array by 1.
Before sorting 14 2 10 5 1 3 17 7
outer=7, inner=0 2 14 10 5 1 3 17 7
outer=7, inner=1 2 10 14 5 1 3 17 7
outer=7, inner=2 2 10 5 14 1 3 17 7
outer=7, inner=3 2 10 5 1 14 3 17 7
outer=7, inner=4 2 10 5 1 3 14 17 7
outer=7, inner=6 2 10 5 1 3 14 7 17
outer=6, inner=1 2 5 10 1 3 14 7 17
outer=6, inner=2 2 5 1 10 3 14 7 17
outer=6, inner=3 2 5 1 3 10 14 7 17
outer=6, inner=5 2 5 1 3 10 7 14 17
outer=5, inner=1 2 1 5 3 10 7 14 17
outer=5, inner=2 2 1 3 5 10 7 14 17
outer=5, inner=4 2 1 3 5 7 10 14 17
outer=4, inner=0 1 2 3 5 7 10 14 17
---
outer=1, inner=0 1 2 3 5 7 10 14 17
//Example1b: Bobble sort
// Sort an array of integers in ascending order
void bubble(int data[], // in/output: array
int size){ // input: array size
int temp; // for swap
for(int outer=size-1; outer > 0; outer--){
for (int inner=0; inner < outer; inner++) {
// traverse the nested loops
if ( data[inner] > data[inner+1] ) {
// swap current element with next
// if the current element is greater
temp = data[inner];
data[inner] = data[inner+1];
data[inner+1] = temp;
}
} // inner for loop
} // outer for loop
}
const int array_size = 12, string_size = 11;
int main() {
char month[array_size][string_size] = {"January",
"February","March","April","May","June","July","August",
"September", "October", "November", "December"};
int index, ans;
cout << "Enter sorting method 1(select), 2(bubble): ";
cin >> ans;
if (ans == 1) select(month, array_size);
else bubble(month, array_size);
cout << endl << "After sorting: ";
for (index = 0; index<array_size; index++)
cout << month[index] <<" ";
cout << endl;
return 0;
}
0 1 2 3 4 5 6 7 8 9 10
month[0] J a n u a r y 0
month[1] F e b r u a r y 0
month[2] M a r c h 0
month[3] A p r i l 0
month[4] M a y 0
month[5] J u n e 0
month[6] J u l y 0
month[7] A u g u s t 0
month[8] S e p t e m b e r 0
month[9] O c t c b e r 0
month[10] N o v e m b e r 0
month[11] D e c e m b e r 0
// Sort array of strings in ascending order
void select(char data[][string_size], // in/output: array
int size){ // input: array size
char temp[string_size]; // for swap
int max_index; // index of max value
for (int rightmost=size-1; rightmost>0; rightmost--){
// find the largest item
max_index = 0;
for(int current=1; current<=rightmost; current++)
if (strcmp(data[current], data[max_index]) >0)
max_index = current;
// swap with last item if necessary
if(strcmp(data[max_index], data[rightmost])>0){
strcpy(temp,data[max_index]); // swap
strcpy(data[max_index],data[rightmost]);
strcpy(data[rightmost], temp);
for (int index=0; index< size; index++)
cout << data[index] << " ";
cout<<endl;
}
}
}
// Sort an array of strings in ascending order
void bubble(char data[][string_size], // in/output:array
int size){ // input: array size
char temp[string_size]; // for swap
for(int outer=size-1 ; outer>0; outer--){
for (int inner=0; inner < outer; inner++) {
// traverse the nested loops
if ( strcmp(data[inner], data[inner+1])>0 )
{
// swap current element with next
// if the current element is greater
strcpy(temp, data[inner]);
strcpy(data[inner], data[inner+1]);
strcpy(data[inner+1], temp);
for (int index=0; index< size; index++)
cout << data[index] << " ";
cout<<endl;
}
} // inner for loop
} // outer for loop
}

Weitere ähnliche Inhalte

Was ist angesagt?

Searching/Sorting algorithms
Searching/Sorting algorithmsSearching/Sorting algorithms
Searching/Sorting algorithmsHuy Nguyen
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting AlgorithmsRahul Jamwal
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsAbdullah Al-hazmy
 
Introduction to Data Structures Sorting and searching
Introduction to Data Structures Sorting and searchingIntroduction to Data Structures Sorting and searching
Introduction to Data Structures Sorting and searchingMvenkatarao
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionarynitamhaske
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSGokul Hari
 
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...Dharmendra Prasad
 
Chapter 14 Searching and Sorting
Chapter 14 Searching and SortingChapter 14 Searching and Sorting
Chapter 14 Searching and SortingMuhammadBakri13
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary searchArjunsinh Jadeja
 
Coin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmCoin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmMd Sadequl Islam
 
Chapter 14
Chapter 14Chapter 14
Chapter 14Terry Yoast
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhithRj Juhith
 
Insertion Sorting
Insertion SortingInsertion Sorting
Insertion SortingFarihaHabib123
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in PythonDevashish Kumar
 
Searching linear &amp; binary search
Searching linear &amp; binary searchSearching linear &amp; binary search
Searching linear &amp; binary searchnikunjandy
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sortingFadhil Ismail
 

Was ist angesagt? (20)

Sorting
SortingSorting
Sorting
 
Searching/Sorting algorithms
Searching/Sorting algorithmsSearching/Sorting algorithms
Searching/Sorting algorithms
 
sort search in C
 sort search in C  sort search in C
sort search in C
 
Searching & Sorting Algorithms
Searching & Sorting AlgorithmsSearching & Sorting Algorithms
Searching & Sorting Algorithms
 
Data Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithmsData Structures- Part3 arrays and searching algorithms
Data Structures- Part3 arrays and searching algorithms
 
Introduction to Data Structures Sorting and searching
Introduction to Data Structures Sorting and searchingIntroduction to Data Structures Sorting and searching
Introduction to Data Structures Sorting and searching
 
1-D array
1-D array1-D array
1-D array
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
SEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMSSEARCHING AND SORTING ALGORITHMS
SEARCHING AND SORTING ALGORITHMS
 
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
Lecture 3  data structures & algorithms - sorting techniques - http://techiem...Lecture 3  data structures & algorithms - sorting techniques - http://techiem...
Lecture 3 data structures & algorithms - sorting techniques - http://techiem...
 
Chapter 14 Searching and Sorting
Chapter 14 Searching and SortingChapter 14 Searching and Sorting
Chapter 14 Searching and Sorting
 
Linear and binary search
Linear and binary searchLinear and binary search
Linear and binary search
 
Coin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - AlgorithmCoin Changing, Binary Search , Linear Search - Algorithm
Coin Changing, Binary Search , Linear Search - Algorithm
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Insertion Sorting
Insertion SortingInsertion Sorting
Insertion Sorting
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Searching linear &amp; binary search
Searching linear &amp; binary searchSearching linear &amp; binary search
Searching linear &amp; binary search
 
(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting(Data Structure) Chapter11 searching & sorting
(Data Structure) Chapter11 searching & sorting
 

Ă„hnlich wie Sorting

Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharpMicheal Ogundero
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arraysmaamir farooq
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & AlgorithumsAin-ul-Moiz Khawaja
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.pptLegesseSamuel
 
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 - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Muhammad Hammad Waseem
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)EngineerBabu
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithmsmultimedia9
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithmsZaid Hameed
 
Sorting Algorithms.
Sorting Algorithms.Sorting Algorithms.
Sorting Algorithms.Saket Kumar
 
16-sorting.ppt
16-sorting.ppt16-sorting.ppt
16-sorting.ppt18Gunaalanpg
 
stacks and queues
stacks and queuesstacks and queues
stacks and queuesDurgaDeviCbit
 
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptxMYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptxArjayBalberan1
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6Dr.Umadevi V
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmEhsan Ehrari
 
Computer notes - Sorting
Computer notes  - SortingComputer notes  - Sorting
Computer notes - Sortingecomputernotes
 
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
 

Ă„hnlich wie Sorting (20)

Sorting
SortingSorting
Sorting
 
Basic Sorting algorithms csharp
Basic Sorting algorithms csharpBasic Sorting algorithms csharp
Basic Sorting algorithms csharp
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
Advanced s and s algorithm.ppt
Advanced s and s algorithm.pptAdvanced s and s algorithm.ppt
Advanced s and s algorithm.ppt
 
simple-sorting algorithms
simple-sorting algorithmssimple-sorting algorithms
simple-sorting algorithms
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
 
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 - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Sorting Algorithms.
Sorting Algorithms.Sorting Algorithms.
Sorting Algorithms.
 
16-sorting.ppt
16-sorting.ppt16-sorting.ppt
16-sorting.ppt
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptxMYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
MYSQL DATABASE MYSQL DATABASE MYSQL DATABASE BUBLESORT.pptx
 
Data Structures 6
Data Structures 6Data Structures 6
Data Structures 6
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in Algoritm
 
Computer notes - Sorting
Computer notes  - SortingComputer notes  - Sorting
Computer notes - 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
 

Mehr von Abhishek Khune

Mehr von Abhishek Khune (16)

07 java collection
07 java collection07 java collection
07 java collection
 
Clanguage
ClanguageClanguage
Clanguage
 
Java Notes
Java NotesJava Notes
Java Notes
 
Threads
ThreadsThreads
Threads
 
Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01Slide8appletv2 091028110313-phpapp01
Slide8appletv2 091028110313-phpapp01
 
Packages in java
Packages in javaPackages in java
Packages in java
 
Week0 introduction
Week0 introductionWeek0 introduction
Week0 introduction
 
Binary trees
Binary treesBinary trees
Binary trees
 
Applets
AppletsApplets
Applets
 
Clanguage
ClanguageClanguage
Clanguage
 
06 abstract-classes
06 abstract-classes06 abstract-classes
06 abstract-classes
 
Java unit3
Java unit3Java unit3
Java unit3
 
Java unit2
Java unit2Java unit2
Java unit2
 
Linux introduction
Linux introductionLinux introduction
Linux introduction
 
Shared memory
Shared memoryShared memory
Shared memory
 
Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)Lecture 14 (inheritance basics)
Lecture 14 (inheritance basics)
 

KĂĽrzlich hochgeladen

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Dr. Mazin Mohamed alkathiri
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
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
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 đź’ž Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 đź’ž Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 đź’ž Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 đź’ž Full Nigh...Pooja Nehwal
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
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
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

KĂĽrzlich hochgeladen (20)

SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
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...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 đź’ž Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 đź’ž Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 đź’ž Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 đź’ž Full Nigh...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.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
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Sorting

  • 2. MP102 Prog. Fundamentals. Sorting I/ Slide 2 Sorting To arrange a set of items in sequence. It is estimated that 25~50% of all computing power is used for sorting activities. Possible reasons: Many applications require sorting; Many applications perform sorting when they don't have to; Many applications use inefficient sorting algorithms.
  • 3. MP102 Prog. Fundamentals. Sorting I/ Slide 3 Sorting Applications To prepare a list of student ID, names, and scores in a table (sorted by ID or name) for easy checking. To prepare a list of scores before letter grade assignment. To produce a list of horses after a race (sorted by the finishing times) for payoff calculation. To prepare an originally unsorted array for ordered binary searching.
  • 4. MP102 Prog. Fundamentals. Sorting I/ Slide 4 Some Sorting Methods Selection sort Bubble sort Shell sort (a simple but faster sorting method than above; see p.331 of Numerical Recipes in C, 2nd ed., by William H. Press et al, Cambridge University Press, 1992) Quick sort (a very efficient sorting method for most applications; p.332-336, ibid.)
  • 5. MP102 Prog. Fundamentals. Sorting I/ Slide 5 Ex. 1A: Selection Sort Selection sort performs sorting by repeatedly putting the largest element in the unsorted portion of the array to the end of this unsorted portion until the whole array is sorted. It is similar to the way that many people do their sorting.
  • 6. MP102 Prog. Fundamentals. Sorting I/ Slide 6 Ex. 1A: Selection Sort Algorithm 1. Define the entire array as the unsorted portion of the array 2. While the unsorted portion of the array has more than one element: ⇒ Find its largest element. ⇒ Swap with last element (assuming their values are different). ⇒ Reduce the size of the unsorted portion of the array by 1.
  • 7. Before sorting 14 2 10 5 1 3 17 7 After pass 1 14 2 10 5 1 3 7 17 After pass 2 7 2 10 5 1 3 14 17 After pass 3 7 2 3 5 1 10 14 17 After pass 4 1 2 3 5 7 10 14 17
  • 8. // Sort array of integers in ascending order void select(int data[], // in/output: array int size){ // input: array size int temp; // for swap int max_index; // index of max value for (int rightmost=size-1; rightmost>0; rightmost--){ //find the largest item in the unsorted portion //rightmost is the end point of the unsorted part of array max_index = 0; //points the largest element for ( int current=1; current<=rightmost; current++) if (data[current] > data[max_index]) max_index = current; //swap the largest item with last item if necessary if (data[max_index] > data[rightmost]){ temp = data[max_index]; // swap data[max_index] = data[rightmost]; data[rightmost] = temp; } }}
  • 9. const int array_size = 8; int main() { int list[array_size] = {14, 2, 10, 5, 1, 3, 17, 7}; int index, ans; cout << "Before sorting: "; for (index = 0; index<array_size; index++) cout << list[index] <<" "; cout << endl; cout << "Enter sorting method 1(select), 2(bubble):"; cin >> ans; if (ans == 1) select(list, array_size); else bubble(list, array_size); cout << endl << "After sorting: "; for (index = 0; index<array_size; index++) cout << list[index] <<" "; cout << endl; return 0; }
  • 10. P102 Prog. Fundamentals. Sorting I/ Slide 10 Ex. 1B: Bubble Sort Bubble sort examines the array from start to finish, comparing elements as it goes. Any time it finds a larger element before a smaller element, it swaps the two. In this way, the larger elements are passed towards the end. The largest element of the array therefore "bubbles" to the end of the array. Then it repeats the process for the unsorted portion of the array until the whole array is sorted.
  • 11. P102 Prog. Fundamentals. Sorting I/ Slide 11 Ex. 1A: Bubble Sort Bubble sort works on the same general principle as shaking a soft drink bottle. Right after shaking, the contents are a mixture of bubbles and soft drink, distributed randomly. Because bubbles are lighter than the soft drink, they rise to the surface, displacing the soft drink downwards. This is how bubble sort got its name, because the smaller elements "float" to the top, while the larger elements "sink" to the bottom.
  • 12. P102 Prog. Fundamentals. Sorting I/ Slide 12 Ex. 1B: Bubble Sort Algorithm Define the entire array as the unsorted portion of the array. While the unsorted portion of the array has more than one element: 1. For every element in the unsorted portion, swap with the next neighbor if it is larger than the neighbor. 2. Reduce the size of the unsorted portion of the array by 1.
  • 13. Before sorting 14 2 10 5 1 3 17 7 outer=7, inner=0 2 14 10 5 1 3 17 7 outer=7, inner=1 2 10 14 5 1 3 17 7 outer=7, inner=2 2 10 5 14 1 3 17 7 outer=7, inner=3 2 10 5 1 14 3 17 7 outer=7, inner=4 2 10 5 1 3 14 17 7 outer=7, inner=6 2 10 5 1 3 14 7 17 outer=6, inner=1 2 5 10 1 3 14 7 17 outer=6, inner=2 2 5 1 10 3 14 7 17 outer=6, inner=3 2 5 1 3 10 14 7 17 outer=6, inner=5 2 5 1 3 10 7 14 17 outer=5, inner=1 2 1 5 3 10 7 14 17 outer=5, inner=2 2 1 3 5 10 7 14 17 outer=5, inner=4 2 1 3 5 7 10 14 17 outer=4, inner=0 1 2 3 5 7 10 14 17 --- outer=1, inner=0 1 2 3 5 7 10 14 17
  • 14. //Example1b: Bobble sort // Sort an array of integers in ascending order void bubble(int data[], // in/output: array int size){ // input: array size int temp; // for swap for(int outer=size-1; outer > 0; outer--){ for (int inner=0; inner < outer; inner++) { // traverse the nested loops if ( data[inner] > data[inner+1] ) { // swap current element with next // if the current element is greater temp = data[inner]; data[inner] = data[inner+1]; data[inner+1] = temp; } } // inner for loop } // outer for loop }
  • 15. const int array_size = 12, string_size = 11; int main() { char month[array_size][string_size] = {"January", "February","March","April","May","June","July","August", "September", "October", "November", "December"}; int index, ans; cout << "Enter sorting method 1(select), 2(bubble): "; cin >> ans; if (ans == 1) select(month, array_size); else bubble(month, array_size); cout << endl << "After sorting: "; for (index = 0; index<array_size; index++) cout << month[index] <<" "; cout << endl; return 0; }
  • 16. 0 1 2 3 4 5 6 7 8 9 10 month[0] J a n u a r y 0 month[1] F e b r u a r y 0 month[2] M a r c h 0 month[3] A p r i l 0 month[4] M a y 0 month[5] J u n e 0 month[6] J u l y 0 month[7] A u g u s t 0 month[8] S e p t e m b e r 0 month[9] O c t c b e r 0 month[10] N o v e m b e r 0 month[11] D e c e m b e r 0
  • 17. // Sort array of strings in ascending order void select(char data[][string_size], // in/output: array int size){ // input: array size char temp[string_size]; // for swap int max_index; // index of max value for (int rightmost=size-1; rightmost>0; rightmost--){ // find the largest item max_index = 0; for(int current=1; current<=rightmost; current++) if (strcmp(data[current], data[max_index]) >0) max_index = current; // swap with last item if necessary if(strcmp(data[max_index], data[rightmost])>0){ strcpy(temp,data[max_index]); // swap strcpy(data[max_index],data[rightmost]); strcpy(data[rightmost], temp); for (int index=0; index< size; index++) cout << data[index] << " "; cout<<endl; } } }
  • 18. // Sort an array of strings in ascending order void bubble(char data[][string_size], // in/output:array int size){ // input: array size char temp[string_size]; // for swap for(int outer=size-1 ; outer>0; outer--){ for (int inner=0; inner < outer; inner++) { // traverse the nested loops if ( strcmp(data[inner], data[inner+1])>0 ) { // swap current element with next // if the current element is greater strcpy(temp, data[inner]); strcpy(data[inner], data[inner+1]); strcpy(data[inner+1], temp); for (int index=0; index< size; index++) cout << data[index] << " "; cout<<endl; } } // inner for loop } // outer for loop }