SlideShare a Scribd company logo
1 of 30
CSE 373
Data Structures and Algorithms
Lecture 7: Sorting
Why Sorting?
2
 Practical application
 People by last name
 Countries by population
 Search engine results by relevance
 Fundamental to other algorithms
 Different algorithms have different asymptotic and
constant-factor trade-offs
 No single ‘best’ sort for all scenarios
 Knowing one way to sort just isn’t enough
 Many to approaches to sorting which can be used for
other problems
Problem statement
3
 There are n comparable elements in an array and we
want to rearrange them to be in increasing order
 Pre:
 An array A of data records
 A value in each data record
 A comparison function
 <, =, >, compareTo
 Post:
 For each distinct position i and j of A, if i<j then A[i] 
A[j]
 A has all the same data it started with
Sorting Classification
4
In memory sorting
External
sorting
Comparison sorting
(N log N)
Specialized
Sorting
O(N2) O(N log N) O(N)
# of tape
accesses
• Bubble Sort
• Selection
Sort
• Insertion
Sort
• Shell Sort
• Merge Sort
• Quick Sort
• Heap Sort
• Bucket Sort
• Radix Sort
• Simple
External
Merge Sort
• Variations
Comparison Sorting
Determine order through comparisons on the input data
Bogo sort
6
 bogo sort: orders a list of values by repetitively
shuffling them and checking if they are sorted
 more specifically:
 scan the list, seeing if it is sorted
 if not, shuffle the values in the list and repeat
 This sorting algorithm has terrible performance!
 Can we deduce its runtime?
 What about best case?
Bogo sort code
7
public static void bogoSort(int[] a) {
while (!isSorted(a)) {
shuffle(a);
}
}
// Returns true if array a's elements
// are in sorted order.
public static boolean isSorted(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
if (a[i] > a[i+1]) {
return false;
}
}
return true;
}
Bogo sort code, helpers
8
// Shuffles an array of ints by randomly swapping each
// element with an element ahead of it in the array.
public static void shuffle(int[] a) {
for (int i = 0; i < a.length - 1; i++) {
// pick random number in [i+1, a.length-1] inclusive
int range = (a.length – 1) - (i + 1) + 1;
int j = (int)(Math.random() * range + (i + 1));
swap(a, i, j);
}
}
// Swaps a[i] with a[j].
private static void swap(int[] a, int i, int j) {
if (i == j)
return;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
O(n2) Comparison Sorting
Bubble sort
10
 bubble sort: orders a list of values by repetitively
comparing neighboring elements and swapping their
positions if necessary
 more specifically:
 scan the list, exchanging adjacent elements if they are not
in relative order; this bubbles the highest value to the top
 scan the list again, bubbling up the second highest value
 repeat until all elements have been placed in their proper
order
"Bubbling" largest element
11
 Traverse a collection of elements
 Move from the front to the end
 "Bubble" the largest value to the end using pair-wise
comparisons and swapping
5
12
35
42
77 101
0 1 2 3 4 5
Swap
42 77
"Bubbling" largest element
12
 Traverse a collection of elements
 Move from the front to the end
 "Bubble" the largest value to the end using pair-wise
comparisons and swapping
5
12
35
77
42 101
0 1 2 3 4 5
Swap
35 77
"Bubbling" largest element
13
 Traverse a collection of elements
 Move from the front to the end
 "Bubble" the largest value to the end using pair-wise
comparisons and swapping
5
12
77
35
42 101
0 1 2 3 4 5
Swap
12 77
"Bubbling" largest element
14
 Traverse a collection of elements
 Move from the front to the end
 "Bubble" the largest value to the end using pair-wise
comparisons and swapping
5
77
12
35
42 101
0 1 2 3 4 5
No need to swap
"Bubbling" largest element
15
 Traverse a collection of elements
 Move from the front to the end
 "Bubble" the largest value to the end using pair-wise
comparisons and swapping
5
77
12
35
42 101
0 1 2 3 4 5
Swap
5 101
"Bubbling" largest element
16
 Traverse a collection of elements
 Move from the front to the end
 "Bubble" the largest value to the end using pair-wise
comparisons and swapping
77
12
35
42 5
0 1 2 3 4 5
101
Largest value correctly placed
Bubble sort code
17
public static void bubbleSort(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < a.length - i; j++) {
// swap adjacent out-of-order elements
if (a[j-1] > a[j]) {
swap(a, j-1, j);
}
}
}
}
Bubble sort runtime
18
 Running time (# comparisons) for input size n:
 number of actual swaps performed depends on the data; out-
of-order data performs many swaps
Selection sort
19
 selection sort: orders a list of values by repetitively
putting a particular value into its final position
 more specifically:
 find the smallest value in the list
 switch it with the value in the first position
 find the next smallest value in the list
 switch it with the value in the second position
 repeat until all values are in their proper places
Selection sort example
20
Index
0 1 2 3 4 5 6 7
Value
27 63 1 72 64 58 14 9
1st pass
1 63 27 72 64 58 14 9
2nd pass
1 9 27 72 64 58 14 63
3rd pass
1 9 14 72 64 58 27 63
…
Selection sort example 2
21
Selection sort code
22
public static void selectionSort(int[] a) {
for (int i = 0; i < a.length; i++) {
// find index of smallest element
int minIndex = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[minIndex]) {
minIndex = j;
}
}
// swap smallest element with a[i]
swap(a, i, minIndex);
}
}
Selection sort runtime
23
 Running time for input size n:
 In practice, a bit faster than bubble sort. Why?
Insertion sort
24
 insertion sort: orders a list of values by repetitively
inserting a particular value into a sorted subset of the
list
 more specifically:
 consider the first item to be a sorted sublist of length 1
 insert the second item into the sorted sublist, shifting the
first item if needed
 insert the third item into the sorted sublist, shifting the
other items as needed
 repeat until all values have been inserted into their proper
positions
Insertion sort
25
 Simple sorting algorithm.
 n-1 passes over the array
 At the end of pass i, the elements that occupied A[0]…A[i]
originally are still in those spots and in sorted order.
2 8 15 1 17 10 12 5
0 1 2 3 4 5 6 7
1 2 8 15 17 10 12 5
0 1 2 3 4 5 6 7
after
pass 2
after
pass 3
2 15 8 1 17 10 12 5
0 1 2 3 4 5 6 7
Insertion sort example
26
Insertion sort code
27
public static void insertionSort(int[] a) {
for (int i = 1; i < a.length; i++) {
int temp = a[i];
// slide elements down to make room for a[i]
int j = i;
while (j > 0 && a[j - 1] > temp) {
a[j] = a[j - 1];
j--;
}
a[j] = temp;
}
}
Insertion sort runtime
28
 worst case: reverse-ordered elements in array.
 best case: array is in sorted ascending order.
 average case: each element is about halfway in order.
Comparing sorts
29
 We've seen "simple" sorting algorithms so far, such
as selection sort and insertion sort.
 They all use nested loops and perform
approximately n2 comparisons
 They are relatively inefficient
Sorting practice problem
30
 Consider the following array of int values.
 [22, 11, 34, -5, 3, 40, 9, 16, 6]
 (a) Write the contents of the array after 3 passes of the
outermost loop of bubble sort.
 (b) Write the contents of the array after 5 passes of the
outermost loop of insertion sort.
 (c) Write the contents of the array after 4 passes of the
outermost loop of selection sort.

More Related Content

Similar to Decimal Long Double Double Double. Represents double-precision floating-point numbers. It can store decimal values and provid

Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingEduardo Bergavera
 
Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.NikhilSoni177492
 
Sorting Algorithms.
Sorting Algorithms.Sorting Algorithms.
Sorting Algorithms.Saket Kumar
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithmspppepito86
 
Sorting_Algoritm-computee-scienceggn.pdf
Sorting_Algoritm-computee-scienceggn.pdfSorting_Algoritm-computee-scienceggn.pdf
Sorting_Algoritm-computee-scienceggn.pdfMohammed472103
 
Bubble sort, Selection sort SORTING .pptx
Bubble sort, Selection sort SORTING .pptxBubble sort, Selection sort SORTING .pptx
Bubble sort, Selection sort SORTING .pptxKalpana Mohan
 
Bin Sorting And Bubble Sort By Luisito G. Trinidad
Bin Sorting And Bubble Sort By Luisito G. TrinidadBin Sorting And Bubble Sort By Luisito G. Trinidad
Bin Sorting And Bubble Sort By Luisito G. TrinidadLUISITO TRINIDAD
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & AlgorithumsAin-ul-Moiz Khawaja
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfNiravPanchal50
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Ra'Fat Al-Msie'deen
 

Similar to Decimal Long Double Double Double. Represents double-precision floating-point numbers. It can store decimal values and provid (20)

Chapter 11 - Sorting and Searching
Chapter 11 - Sorting and SearchingChapter 11 - Sorting and Searching
Chapter 11 - Sorting and Searching
 
Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.Sorting and Hashing Algorithm full pdfs.
Sorting and Hashing Algorithm full pdfs.
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Sorting
SortingSorting
Sorting
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Sorting Algorithms.
Sorting Algorithms.Sorting Algorithms.
Sorting Algorithms.
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
Sorting
SortingSorting
Sorting
 
Sorting_Algoritm-computee-scienceggn.pdf
Sorting_Algoritm-computee-scienceggn.pdfSorting_Algoritm-computee-scienceggn.pdf
Sorting_Algoritm-computee-scienceggn.pdf
 
Sorting
SortingSorting
Sorting
 
Sorting
SortingSorting
Sorting
 
Bubble sort, Selection sort SORTING .pptx
Bubble sort, Selection sort SORTING .pptxBubble sort, Selection sort SORTING .pptx
Bubble sort, Selection sort SORTING .pptx
 
Sorting techniques
Sorting techniques Sorting techniques
Sorting techniques
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
 
Bin Sorting And Bubble Sort By Luisito G. Trinidad
Bin Sorting And Bubble Sort By Luisito G. TrinidadBin Sorting And Bubble Sort By Luisito G. Trinidad
Bin Sorting And Bubble Sort By Luisito G. Trinidad
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
Java Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdfJava Algorithm Interview Questions & Answers .pdf
Java Algorithm Interview Questions & Answers .pdf
 
Unit 7 sorting
Unit   7 sortingUnit   7 sorting
Unit 7 sorting
 
Arrays
ArraysArrays
Arrays
 
Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"Algorithms - "Chapter 2 getting started"
Algorithms - "Chapter 2 getting started"
 

Recently uploaded

Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...Diya Sharma
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$kojalkojal131
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girladitipandeya
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024APNIC
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girlsstephieert
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsThierry TROUIN ☁
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxellan12
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of indiaimessage0108
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Roomgirls4nights
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneCall girls in Ahmedabad High profile
 

Recently uploaded (20)

Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Defence Colony Delhi 💯Call Us 🔝8264348440🔝
 
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
₹5.5k {Cash Payment}New Friends Colony Call Girls In [Delhi NIHARIKA] 🔝|97111...
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
Call Girls Dubai Prolapsed O525547819 Call Girls In Dubai Princes$
 
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call GirlVIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
VIP 7001035870 Find & Meet Hyderabad Call Girls LB Nagar high-profile Call Girl
 
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 
On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024On Starlink, presented by Geoff Huston at NZNOG 2024
On Starlink, presented by Geoff Huston at NZNOG 2024
 
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
10.pdfMature Call girls in Dubai +971563133746 Dubai Call girls
 
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 6 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Model Towh Delhi 💯Call Us 🔝8264348440🔝
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
AlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with FlowsAlbaniaDreamin24 - How to easily use an API with Flows
AlbaniaDreamin24 - How to easily use an API with Flows
 
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptxAWS Community DAY Albertini-Ellan Cloud Security (1).pptx
AWS Community DAY Albertini-Ellan Cloud Security (1).pptx
 
Gram Darshan PPT cyber rural in villages of india
Gram Darshan PPT cyber rural  in villages of indiaGram Darshan PPT cyber rural  in villages of india
Gram Darshan PPT cyber rural in villages of india
 
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With RoomVIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
VIP Kolkata Call Girls Salt Lake 8250192130 Available With Room
 
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls KolkataVIP Call Girls Kolkata Ananya 🤌  8250192130 🚀 Vip Call Girls Kolkata
VIP Call Girls Kolkata Ananya 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in  Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Jamuna Vihar Delhi reach out to us at 🔝9953056974🔝
 
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service PuneVIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
VIP Call Girls Pune Madhuri 8617697112 Independent Escort Service Pune
 

Decimal Long Double Double Double. Represents double-precision floating-point numbers. It can store decimal values and provid

  • 1. CSE 373 Data Structures and Algorithms Lecture 7: Sorting
  • 2. Why Sorting? 2  Practical application  People by last name  Countries by population  Search engine results by relevance  Fundamental to other algorithms  Different algorithms have different asymptotic and constant-factor trade-offs  No single ‘best’ sort for all scenarios  Knowing one way to sort just isn’t enough  Many to approaches to sorting which can be used for other problems
  • 3. Problem statement 3  There are n comparable elements in an array and we want to rearrange them to be in increasing order  Pre:  An array A of data records  A value in each data record  A comparison function  <, =, >, compareTo  Post:  For each distinct position i and j of A, if i<j then A[i]  A[j]  A has all the same data it started with
  • 4. Sorting Classification 4 In memory sorting External sorting Comparison sorting (N log N) Specialized Sorting O(N2) O(N log N) O(N) # of tape accesses • Bubble Sort • Selection Sort • Insertion Sort • Shell Sort • Merge Sort • Quick Sort • Heap Sort • Bucket Sort • Radix Sort • Simple External Merge Sort • Variations
  • 5. Comparison Sorting Determine order through comparisons on the input data
  • 6. Bogo sort 6  bogo sort: orders a list of values by repetitively shuffling them and checking if they are sorted  more specifically:  scan the list, seeing if it is sorted  if not, shuffle the values in the list and repeat  This sorting algorithm has terrible performance!  Can we deduce its runtime?  What about best case?
  • 7. Bogo sort code 7 public static void bogoSort(int[] a) { while (!isSorted(a)) { shuffle(a); } } // Returns true if array a's elements // are in sorted order. public static boolean isSorted(int[] a) { for (int i = 0; i < a.length - 1; i++) { if (a[i] > a[i+1]) { return false; } } return true; }
  • 8. Bogo sort code, helpers 8 // Shuffles an array of ints by randomly swapping each // element with an element ahead of it in the array. public static void shuffle(int[] a) { for (int i = 0; i < a.length - 1; i++) { // pick random number in [i+1, a.length-1] inclusive int range = (a.length – 1) - (i + 1) + 1; int j = (int)(Math.random() * range + (i + 1)); swap(a, i, j); } } // Swaps a[i] with a[j]. private static void swap(int[] a, int i, int j) { if (i == j) return; int temp = a[i]; a[i] = a[j]; a[j] = temp; }
  • 10. Bubble sort 10  bubble sort: orders a list of values by repetitively comparing neighboring elements and swapping their positions if necessary  more specifically:  scan the list, exchanging adjacent elements if they are not in relative order; this bubbles the highest value to the top  scan the list again, bubbling up the second highest value  repeat until all elements have been placed in their proper order
  • 11. "Bubbling" largest element 11  Traverse a collection of elements  Move from the front to the end  "Bubble" the largest value to the end using pair-wise comparisons and swapping 5 12 35 42 77 101 0 1 2 3 4 5 Swap 42 77
  • 12. "Bubbling" largest element 12  Traverse a collection of elements  Move from the front to the end  "Bubble" the largest value to the end using pair-wise comparisons and swapping 5 12 35 77 42 101 0 1 2 3 4 5 Swap 35 77
  • 13. "Bubbling" largest element 13  Traverse a collection of elements  Move from the front to the end  "Bubble" the largest value to the end using pair-wise comparisons and swapping 5 12 77 35 42 101 0 1 2 3 4 5 Swap 12 77
  • 14. "Bubbling" largest element 14  Traverse a collection of elements  Move from the front to the end  "Bubble" the largest value to the end using pair-wise comparisons and swapping 5 77 12 35 42 101 0 1 2 3 4 5 No need to swap
  • 15. "Bubbling" largest element 15  Traverse a collection of elements  Move from the front to the end  "Bubble" the largest value to the end using pair-wise comparisons and swapping 5 77 12 35 42 101 0 1 2 3 4 5 Swap 5 101
  • 16. "Bubbling" largest element 16  Traverse a collection of elements  Move from the front to the end  "Bubble" the largest value to the end using pair-wise comparisons and swapping 77 12 35 42 5 0 1 2 3 4 5 101 Largest value correctly placed
  • 17. Bubble sort code 17 public static void bubbleSort(int[] a) { for (int i = 0; i < a.length; i++) { for (int j = 1; j < a.length - i; j++) { // swap adjacent out-of-order elements if (a[j-1] > a[j]) { swap(a, j-1, j); } } } }
  • 18. Bubble sort runtime 18  Running time (# comparisons) for input size n:  number of actual swaps performed depends on the data; out- of-order data performs many swaps
  • 19. Selection sort 19  selection sort: orders a list of values by repetitively putting a particular value into its final position  more specifically:  find the smallest value in the list  switch it with the value in the first position  find the next smallest value in the list  switch it with the value in the second position  repeat until all values are in their proper places
  • 21. Index 0 1 2 3 4 5 6 7 Value 27 63 1 72 64 58 14 9 1st pass 1 63 27 72 64 58 14 9 2nd pass 1 9 27 72 64 58 14 63 3rd pass 1 9 14 72 64 58 27 63 … Selection sort example 2 21
  • 22. Selection sort code 22 public static void selectionSort(int[] a) { for (int i = 0; i < a.length; i++) { // find index of smallest element int minIndex = i; for (int j = i + 1; j < a.length; j++) { if (a[j] < a[minIndex]) { minIndex = j; } } // swap smallest element with a[i] swap(a, i, minIndex); } }
  • 23. Selection sort runtime 23  Running time for input size n:  In practice, a bit faster than bubble sort. Why?
  • 24. Insertion sort 24  insertion sort: orders a list of values by repetitively inserting a particular value into a sorted subset of the list  more specifically:  consider the first item to be a sorted sublist of length 1  insert the second item into the sorted sublist, shifting the first item if needed  insert the third item into the sorted sublist, shifting the other items as needed  repeat until all values have been inserted into their proper positions
  • 25. Insertion sort 25  Simple sorting algorithm.  n-1 passes over the array  At the end of pass i, the elements that occupied A[0]…A[i] originally are still in those spots and in sorted order. 2 8 15 1 17 10 12 5 0 1 2 3 4 5 6 7 1 2 8 15 17 10 12 5 0 1 2 3 4 5 6 7 after pass 2 after pass 3 2 15 8 1 17 10 12 5 0 1 2 3 4 5 6 7
  • 27. Insertion sort code 27 public static void insertionSort(int[] a) { for (int i = 1; i < a.length; i++) { int temp = a[i]; // slide elements down to make room for a[i] int j = i; while (j > 0 && a[j - 1] > temp) { a[j] = a[j - 1]; j--; } a[j] = temp; } }
  • 28. Insertion sort runtime 28  worst case: reverse-ordered elements in array.  best case: array is in sorted ascending order.  average case: each element is about halfway in order.
  • 29. Comparing sorts 29  We've seen "simple" sorting algorithms so far, such as selection sort and insertion sort.  They all use nested loops and perform approximately n2 comparisons  They are relatively inefficient
  • 30. Sorting practice problem 30  Consider the following array of int values.  [22, 11, 34, -5, 3, 40, 9, 16, 6]  (a) Write the contents of the array after 3 passes of the outermost loop of bubble sort.  (b) Write the contents of the array after 5 passes of the outermost loop of insertion sort.  (c) Write the contents of the array after 4 passes of the outermost loop of selection sort.