SlideShare a Scribd company logo
1 of 18
Programming
Sorting
Arrays
COMP102 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.
COMP102 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.
COMP102 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.)
COMP102 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.
COMP102 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;
}
COMP102 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.
COMP102 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.
COMP102 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
}

More Related Content

What's hot

SAS and R Code for Basic Statistics
SAS and R Code for Basic StatisticsSAS and R Code for Basic Statistics
SAS and R Code for Basic StatisticsAvjinder (Avi) Kaler
 
College Algebra 5.2
College Algebra 5.2College Algebra 5.2
College Algebra 5.2Jeneva Clark
 
Data manipulation on r
Data manipulation on rData manipulation on r
Data manipulation on rAbhik Seal
 
Clips basics how to make expert system in clips | facts adding | rules makin...
Clips basics  how to make expert system in clips | facts adding | rules makin...Clips basics  how to make expert system in clips | facts adding | rules makin...
Clips basics how to make expert system in clips | facts adding | rules makin...NaumanMalik30
 
The Ring programming language version 1.2 book - Part 10 of 84
The Ring programming language version 1.2 book - Part 10 of 84The Ring programming language version 1.2 book - Part 10 of 84
The Ring programming language version 1.2 book - Part 10 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84Mahmoud Samir Fayed
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...davidwarner122
 
The Ring programming language version 1.2 book - Part 11 of 84
The Ring programming language version 1.2 book - Part 11 of 84The Ring programming language version 1.2 book - Part 11 of 84
The Ring programming language version 1.2 book - Part 11 of 84Mahmoud Samir Fayed
 
The Ring programming language version 1.2 book - Part 9 of 84
The Ring programming language version 1.2 book - Part 9 of 84The Ring programming language version 1.2 book - Part 9 of 84
The Ring programming language version 1.2 book - Part 9 of 84Mahmoud Samir Fayed
 
Code rule
Code ruleCode rule
Code ruleWei Sun
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
 
R code descriptive statistics of phenotypic data by Avjinder Kaler
R code descriptive statistics of phenotypic data by Avjinder KalerR code descriptive statistics of phenotypic data by Avjinder Kaler
R code descriptive statistics of phenotypic data by Avjinder KalerAvjinder (Avi) Kaler
 
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
 

What's hot (16)

Flight Data Analysis
Flight Data AnalysisFlight Data Analysis
Flight Data Analysis
 
SAS and R Code for Basic Statistics
SAS and R Code for Basic StatisticsSAS and R Code for Basic Statistics
SAS and R Code for Basic Statistics
 
College Algebra 5.2
College Algebra 5.2College Algebra 5.2
College Algebra 5.2
 
Data manipulation on r
Data manipulation on rData manipulation on r
Data manipulation on r
 
Clips basics how to make expert system in clips | facts adding | rules makin...
Clips basics  how to make expert system in clips | facts adding | rules makin...Clips basics  how to make expert system in clips | facts adding | rules makin...
Clips basics how to make expert system in clips | facts adding | rules makin...
 
The Ring programming language version 1.2 book - Part 10 of 84
The Ring programming language version 1.2 book - Part 10 of 84The Ring programming language version 1.2 book - Part 10 of 84
The Ring programming language version 1.2 book - Part 10 of 84
 
The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84The Ring programming language version 1.2 book - Part 12 of 84
The Ring programming language version 1.2 book - Part 12 of 84
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
 
The Ring programming language version 1.2 book - Part 11 of 84
The Ring programming language version 1.2 book - Part 11 of 84The Ring programming language version 1.2 book - Part 11 of 84
The Ring programming language version 1.2 book - Part 11 of 84
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
The Ring programming language version 1.2 book - Part 9 of 84
The Ring programming language version 1.2 book - Part 9 of 84The Ring programming language version 1.2 book - Part 9 of 84
The Ring programming language version 1.2 book - Part 9 of 84
 
Code rule
Code ruleCode rule
Code rule
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
 
Pemrograman Terstruktur 4
Pemrograman Terstruktur 4Pemrograman Terstruktur 4
Pemrograman Terstruktur 4
 
R code descriptive statistics of phenotypic data by Avjinder Kaler
R code descriptive statistics of phenotypic data by Avjinder KalerR code descriptive statistics of phenotypic data by Avjinder Kaler
R code descriptive statistics of phenotypic data by Avjinder Kaler
 
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
 

Similar to 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
 
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
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithmsmultimedia9
 
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
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithmsZaid Hameed
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)EngineerBabu
 
one main advantage of bubble sort as compared to others
one main advantage of bubble sort as compared to othersone main advantage of bubble sort as compared to others
one main advantage of bubble sort as compared to othersAjay Chimmani
 
Shell sorting
Shell sortingShell sorting
Shell sortingTUC
 
Sorting Algorithms.
Sorting Algorithms.Sorting Algorithms.
Sorting Algorithms.Saket Kumar
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmEhsan Ehrari
 

Similar to 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
 
sorting.pptx
sorting.pptxsorting.pptx
sorting.pptx
 
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
 
stacks and queues
stacks and queuesstacks and queues
stacks and queues
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
16-sorting.ppt
16-sorting.ppt16-sorting.ppt
16-sorting.ppt
 
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
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
one main advantage of bubble sort as compared to others
one main advantage of bubble sort as compared to othersone main advantage of bubble sort as compared to others
one main advantage of bubble sort as compared to others
 
Shell sorting
Shell sortingShell sorting
Shell sorting
 
611+tutorial
611+tutorial611+tutorial
611+tutorial
 
Sorting Algorithms.
Sorting Algorithms.Sorting Algorithms.
Sorting Algorithms.
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in Algoritm
 

Recently uploaded

Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for BeginnersSabitha Banu
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxEyham Joco
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...jaredbarbolino94
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 

Recently uploaded (20)

Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Full Stack Web Development Course for Beginners
Full Stack Web Development Course  for BeginnersFull Stack Web Development Course  for Beginners
Full Stack Web Development Course for Beginners
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Types of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptxTypes of Journalistic Writing Grade 8.pptx
Types of Journalistic Writing Grade 8.pptx
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...Historical philosophical, theoretical, and legal foundations of special and i...
Historical philosophical, theoretical, and legal foundations of special and i...
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)ESSENTIAL of (CS/IT/IS) class 06 (database)
ESSENTIAL of (CS/IT/IS) class 06 (database)
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 

Sorting

  • 2. COMP102 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. COMP102 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. COMP102 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. COMP102 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. COMP102 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. COMP102 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. COMP102 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. COMP102 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 }