SlideShare una empresa de Scribd logo
1 de 38
 A sorting technique that sequences data by
continuously merging items in the list, every
single item in the original unordered list is
merged with another, creating groups of two.
Every two-item group is merged, creating
groups of four and so on until there is one
ordered list. See sort algorithm and merge.
 Invented by an American mathematician John
von Neumann in 1945
 One of the first sorting styles proposed for
computers
Top-down implementation
 Top down merge sort algorithm that
recursively splits the list (called runs in this
example) into sublists until sublist size is 1,
then merges those sublists to produce a
sorted list. The copy back step is avoided
with alternating the direction of the merge
with each level of recursion.
Bottom-up implementation
 Bottom up merge sort algorithm which treats the
list as an array of n sublists (called runs in this
example) of size 1, and iteratively merges sub-
lists back and forth between two buffers:

 Top down merge sort algorithm which recursively
divides the input list into smaller sublists until
the sublists are trivially sorted, and then merges
the sublists while returning up the call chain.
To understand merge sort, we take an
unsorted array as the following −
We see here that an array of 6 items is divided
into two arrays of size 3.
23 8 3 13 88 87
23 8 3 13 88 87
Now we divide these two arrays into two’s and
one’s.
We further divide these arrays and we achieve
atomic value which can no more be divided.
23 8 3 13 88 87
23 8 3 13 88 87
We first compare the element for each list and
then combine them into another list in a sorted
manner. We compare 23 and 8 in the target list
and we put 8 first then 23. Since 3 has no
partner we put it in same place. We can see
that 13 and 88 are already sorted so we put
them sequentially followed by 87.
238 3 13 88 87
In the next iteration of the combining phase,
we compare lists of two data values, and merge
them into a list of found data values placing all
in a sorted order.
After the final merging, the list should look like
this −
2383 13 8887
83 13 23 87 88
#include <iostream>
using namespace std;
// A function to merge the two half into a sorted data.
void Merge(int *a, int low, int high, int mid)
{
// We have low to mid and mid+1 to high already
sorted.
int i, j, k, temp[high-low+1];
i = low;
k = 0;
j = mid + 1;
// Merge the two parts into temp[].
while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
temp[k] = a[i];
k++;
i++;
}
else
{
temp[k] = a[j];
k++;
j++;
}
}
// Insert all the remaining values from i to mid
into temp[].
while (i <= mid)
{
temp[k] = a[i];
k++;
i++;
}
// Insert all the remaining values from j to high
into temp[].
while (i <= mid)
{
temp[k] = a[j];
k++;
j++;
}
// Assign sorted data stored in temp[] to a[].
for (i = low; i <= high; i++)
{
a[i] = temp[i-low];
}
}
// A function to split array into two parts.
void MergeSort(int *a, int low, int high)
{
int mid;
if (low < high)
{
mid=(low+high)/2;
// Split the data into two half.
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
// Merge them to get sorted output.
Merge(a, low, high, mid);
}
}
int main()
{
int n, i;
cout<<"nEnter the number of data element to
be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}
MergeSort(arr, 0, n-1);
// Printing the sorted data.
cout<<"nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
 Unsorted Data : 23, 8 ,3 ,13 ,8 ,87
 In computer science, radix sort is a non-
comparative integer sorting algorithm that
sorts data with integer keys by grouping keys
by the individual digits which share the same
significant position and value.
 Radix Sort dates back as far as 1887 to the
work of Herman Hollerith on tabulating
machines.
 Radix Sort is an algorithm that sorts a list of
numbers and comes under the category of
distribution sort
Least Significant Digit (LSD)
 A least significant digit (LSD) Radix Sort is a fast
stable sorting algorithm which can be used to
sort keys in integer representation order.
 Keys may be a string of characters, or numerical
digits in a given ‘radix’.
 The processing of the keys begins at the least
significant digit (the rightmost digit), and
proceeds to the most significant digit (the
leftmost digit).
Most Significant Digit (MSD)
 A most significant digit (MSD) radix sort can
be used to sort keys in lexicographic order.
 Unlike a least significant digit (LSD) radix
sort, a most significant digit radix sort does
not necessarily preserve the original order of
duplicate keys.
 An MSD radix sort starts processing the keys
from the most significant digit, leftmost digit,
to the least significant digit, rightmost digit
Radix sort works by sorting each digit from least
significant digit to most significant digit. Consider this
example:
88, 8, 23, 3, 2, 29, 177, 40
Our task is to sort them in ascending order. Since there
are 10 digits from 0 to 9 so we need to label arrays
from 0 to 9. So 177 is the biggest number among the
unsorted array and it has 3 digits. We will fill all the
numbers with 0s that are smaller than 177. It goes like
this:
088, 008, 023, 003, 002, 029, 177, 040
Since all of them have 3 digits this will require
3 pass.
Pass 1: sort the arrays using first digit from the
right most part.
088, 008, 023, 003, 002, 029, 177, 040
Pass 1 is complete.
04
0
00
2
00
3
02
3
17
7
00
8
08
8
02
9
Take the numbers from the bucket and arrange
them from bottom to top.
040, 002, 023, 003, 177, 088, 008, 029
Pass 2: Sort the numbers by using the 2nd digit
from right.
040, 002, 023, 003, 177, 088, 008, 029
Pass 2 is complete.
00
8
00
3
00
2
02
9
02
3
04
0
17
7
08
8
Take the numbers from the bucket and arrange them from
bottom to top. It should be arranged like this.
002, 003, 008, 023, 029, 040, 177, 088
Pass 3: Sort the numbers by using the 3rd digit
from left.
002, 003, 008, 023, 029, 040, 177, 088
088
040
029
023
008
003
002
177
Pass 3 is complete.
Take the numbers from the bucket and
arrange them from bottom to top.
002, 003, 008, 023, 029, 040, 088, 177
We have completed the 3 passes so we will
now stop here. Remove now all the leading
0s.
2, 3, 8, 23, 29, 40, 88, 177
So the numbers are now sorted in
ascending order.
#include <iostream>
using namespace std;
// A utility function to get maximum value in arr[]
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
// A function to do counting sort of arr[] according
to
// the digit represented by exp.
void countSort(int arr[], int n, int exp)
{
int output[n]; // output array
int i, count[10] = {0};
// Store count of occurrences in count[]
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
// Change count[i] so that count[i] now contains
actual
// position of this digit in output[]
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
// Build the output array
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
// Copy the output array to arr[], so that arr[] now
// contains sorted numbers according to current
digit
for (i = 0; i < n; i++)
arr[i] = output[i];
}
// The main function to that sorts arr[] of size n
using
// Radix Sort
void radixsort(int arr[], int n)
{
// Find the maximum number to know number of
digits
int m = getMax(arr, n);
// Do counting sort for every digit. Note that
instead
// of passing digit number, exp is passed. exp
is 10^i
// where i is current digit number
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
// A utility function to print an array
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
// Driver program to test above functions
int main()
{
// arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
//int n = sizeof(arr)/sizeof(arr[0]);
int n;
cout << "How many numbers? "; cin >> n;
int arr[n];
cout << "Enter the numbers:n";
for (int i = 0;i < n;i++) {
cout << "t";
cin >> arr[i];
}
radixsort(arr, n);
print(arr, n);
return 0;
}
Unsorted array a = {3, 10, 9, 8, 53, 2, 62, 71}

Más contenido relacionado

La actualidad más candente

Лекция 6: Словари. Хеш-таблицы
Лекция 6: Словари. Хеш-таблицыЛекция 6: Словари. Хеш-таблицы
Лекция 6: Словари. Хеш-таблицы
Mikhail Kurnosov
 

La actualidad más candente (20)

Class 5 - PHP Strings
Class 5 - PHP StringsClass 5 - PHP Strings
Class 5 - PHP Strings
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
 
Heap sort
Heap sort Heap sort
Heap sort
 
Class 3 - PHP Functions
Class 3 - PHP FunctionsClass 3 - PHP Functions
Class 3 - PHP Functions
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Php string function
Php string function Php string function
Php string function
 
Asp.net basic
Asp.net basicAsp.net basic
Asp.net basic
 
Kirtesh Khandelwal,Project on HTML and CSS ,Final Year BCA , Dezyne E'cole Co...
Kirtesh Khandelwal,Project on HTML and CSS ,Final Year BCA , Dezyne E'cole Co...Kirtesh Khandelwal,Project on HTML and CSS ,Final Year BCA , Dezyne E'cole Co...
Kirtesh Khandelwal,Project on HTML and CSS ,Final Year BCA , Dezyne E'cole Co...
 
Stack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data StructureStack & Queue using Linked List in Data Structure
Stack & Queue using Linked List in Data Structure
 
Form Handling using PHP
Form Handling using PHPForm Handling using PHP
Form Handling using PHP
 
CS6611 Mobile Application Development Lab Manual-2018-19
CS6611 Mobile Application Development Lab Manual-2018-19CS6611 Mobile Application Development Lab Manual-2018-19
CS6611 Mobile Application Development Lab Manual-2018-19
 
Lesson 6 php if...else...elseif statements
Lesson 6   php if...else...elseif statementsLesson 6   php if...else...elseif statements
Lesson 6 php if...else...elseif statements
 
Лекция 6: Словари. Хеш-таблицы
Лекция 6: Словари. Хеш-таблицыЛекция 6: Словари. Хеш-таблицы
Лекция 6: Словари. Хеш-таблицы
 
Java Multiple Choice Questions and Answers
Java Multiple Choice Questions and AnswersJava Multiple Choice Questions and Answers
Java Multiple Choice Questions and Answers
 
Php forms
Php formsPhp forms
Php forms
 
Analysis of Algorithm (Bubblesort and Quicksort)
Analysis of Algorithm (Bubblesort and Quicksort)Analysis of Algorithm (Bubblesort and Quicksort)
Analysis of Algorithm (Bubblesort and Quicksort)
 
Form validation client side
Form validation client side Form validation client side
Form validation client side
 
DSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdfDSA Lab Manual C Scheme.pdf
DSA Lab Manual C Scheme.pdf
 
Presentation on queue
Presentation on queuePresentation on queue
Presentation on queue
 

Similar a Merge radix-sort-algorithm

Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdf
ankit11134
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
Terry Yoast
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
aroraopticals15
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 

Similar a Merge radix-sort-algorithm (20)

data structures and algorithms Unit 3
data structures and algorithms Unit 3data structures and algorithms Unit 3
data structures and algorithms Unit 3
 
Sorting
SortingSorting
Sorting
 
Please help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdfPlease help solve this in C++ So the program is working fin.pdf
Please help solve this in C++ So the program is working fin.pdf
 
Address calculation-sort
Address calculation-sortAddress calculation-sort
Address calculation-sort
 
Heap, quick and merge sort
Heap, quick and merge sortHeap, quick and merge sort
Heap, quick and merge sort
 
DS Unit 1.pptx
DS Unit 1.pptxDS Unit 1.pptx
DS Unit 1.pptx
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
9781439035665 ppt ch09
9781439035665 ppt ch099781439035665 ppt ch09
9781439035665 ppt ch09
 
Python list
Python listPython list
Python list
 
Chap09
Chap09Chap09
Chap09
 
Homework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdfHomework Assignment – Array Technical DocumentWrite a technical .pdf
Homework Assignment – Array Technical DocumentWrite a technical .pdf
 
Array assignment
Array assignmentArray assignment
Array assignment
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 
Recursion Lecture in C++
Recursion Lecture in C++Recursion Lecture in C++
Recursion Lecture in C++
 
Advance excel
Advance excelAdvance excel
Advance excel
 
DSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notesDSA UNIT II ARRAY AND LIST - notes
DSA UNIT II ARRAY AND LIST - notes
 
Array
ArrayArray
Array
 
Python - Data Collection
Python - Data CollectionPython - Data Collection
Python - Data Collection
 
Python reference
Python referencePython reference
Python reference
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 

Último

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
PECB
 
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
SoniaTolstoy
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 

Último (20)

Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
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
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
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
 
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
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
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 Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
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
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 

Merge radix-sort-algorithm

  • 1.
  • 2.  A sorting technique that sequences data by continuously merging items in the list, every single item in the original unordered list is merged with another, creating groups of two. Every two-item group is merged, creating groups of four and so on until there is one ordered list. See sort algorithm and merge.
  • 3.  Invented by an American mathematician John von Neumann in 1945  One of the first sorting styles proposed for computers
  • 4. Top-down implementation  Top down merge sort algorithm that recursively splits the list (called runs in this example) into sublists until sublist size is 1, then merges those sublists to produce a sorted list. The copy back step is avoided with alternating the direction of the merge with each level of recursion.
  • 5. Bottom-up implementation  Bottom up merge sort algorithm which treats the list as an array of n sublists (called runs in this example) of size 1, and iteratively merges sub- lists back and forth between two buffers:   Top down merge sort algorithm which recursively divides the input list into smaller sublists until the sublists are trivially sorted, and then merges the sublists while returning up the call chain.
  • 6. To understand merge sort, we take an unsorted array as the following − We see here that an array of 6 items is divided into two arrays of size 3. 23 8 3 13 88 87 23 8 3 13 88 87
  • 7. Now we divide these two arrays into two’s and one’s. We further divide these arrays and we achieve atomic value which can no more be divided. 23 8 3 13 88 87 23 8 3 13 88 87
  • 8. We first compare the element for each list and then combine them into another list in a sorted manner. We compare 23 and 8 in the target list and we put 8 first then 23. Since 3 has no partner we put it in same place. We can see that 13 and 88 are already sorted so we put them sequentially followed by 87. 238 3 13 88 87
  • 9. In the next iteration of the combining phase, we compare lists of two data values, and merge them into a list of found data values placing all in a sorted order. After the final merging, the list should look like this − 2383 13 8887 83 13 23 87 88
  • 10. #include <iostream> using namespace std; // A function to merge the two half into a sorted data. void Merge(int *a, int low, int high, int mid) { // We have low to mid and mid+1 to high already sorted. int i, j, k, temp[high-low+1]; i = low; k = 0; j = mid + 1;
  • 11. // Merge the two parts into temp[]. while (i <= mid && j <= high) { if (a[i] < a[j]) { temp[k] = a[i]; k++; i++; }
  • 13. // Insert all the remaining values from i to mid into temp[]. while (i <= mid) { temp[k] = a[i]; k++; i++; }
  • 14. // Insert all the remaining values from j to high into temp[]. while (i <= mid) { temp[k] = a[j]; k++; j++; }
  • 15. // Assign sorted data stored in temp[] to a[]. for (i = low; i <= high; i++) { a[i] = temp[i-low]; } }
  • 16. // A function to split array into two parts. void MergeSort(int *a, int low, int high) { int mid; if (low < high) { mid=(low+high)/2; // Split the data into two half. MergeSort(a, low, mid); MergeSort(a, mid+1, high); // Merge them to get sorted output. Merge(a, low, high, mid); } }
  • 17. int main() { int n, i; cout<<"nEnter the number of data element to be sorted: "; cin>>n; int arr[n]; for(i = 0; i < n; i++) { cout<<"Enter element "<<i+1<<": "; cin>>arr[i]; }
  • 18. MergeSort(arr, 0, n-1); // Printing the sorted data. cout<<"nSorted Data "; for (i = 0; i < n; i++) cout<<"->"<<arr[i]; return 0; }
  • 19.  Unsorted Data : 23, 8 ,3 ,13 ,8 ,87
  • 20.
  • 21.  In computer science, radix sort is a non- comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.
  • 22.  Radix Sort dates back as far as 1887 to the work of Herman Hollerith on tabulating machines.  Radix Sort is an algorithm that sorts a list of numbers and comes under the category of distribution sort
  • 23. Least Significant Digit (LSD)  A least significant digit (LSD) Radix Sort is a fast stable sorting algorithm which can be used to sort keys in integer representation order.  Keys may be a string of characters, or numerical digits in a given ‘radix’.  The processing of the keys begins at the least significant digit (the rightmost digit), and proceeds to the most significant digit (the leftmost digit).
  • 24. Most Significant Digit (MSD)  A most significant digit (MSD) radix sort can be used to sort keys in lexicographic order.  Unlike a least significant digit (LSD) radix sort, a most significant digit radix sort does not necessarily preserve the original order of duplicate keys.  An MSD radix sort starts processing the keys from the most significant digit, leftmost digit, to the least significant digit, rightmost digit
  • 25. Radix sort works by sorting each digit from least significant digit to most significant digit. Consider this example: 88, 8, 23, 3, 2, 29, 177, 40 Our task is to sort them in ascending order. Since there are 10 digits from 0 to 9 so we need to label arrays from 0 to 9. So 177 is the biggest number among the unsorted array and it has 3 digits. We will fill all the numbers with 0s that are smaller than 177. It goes like this: 088, 008, 023, 003, 002, 029, 177, 040
  • 26. Since all of them have 3 digits this will require 3 pass. Pass 1: sort the arrays using first digit from the right most part. 088, 008, 023, 003, 002, 029, 177, 040 Pass 1 is complete. 04 0 00 2 00 3 02 3 17 7 00 8 08 8 02 9
  • 27. Take the numbers from the bucket and arrange them from bottom to top. 040, 002, 023, 003, 177, 088, 008, 029 Pass 2: Sort the numbers by using the 2nd digit from right. 040, 002, 023, 003, 177, 088, 008, 029 Pass 2 is complete. 00 8 00 3 00 2 02 9 02 3 04 0 17 7 08 8
  • 28. Take the numbers from the bucket and arrange them from bottom to top. It should be arranged like this. 002, 003, 008, 023, 029, 040, 177, 088 Pass 3: Sort the numbers by using the 3rd digit from left. 002, 003, 008, 023, 029, 040, 177, 088 088 040 029 023 008 003 002 177
  • 29. Pass 3 is complete. Take the numbers from the bucket and arrange them from bottom to top. 002, 003, 008, 023, 029, 040, 088, 177 We have completed the 3 passes so we will now stop here. Remove now all the leading 0s. 2, 3, 8, 23, 29, 40, 88, 177 So the numbers are now sorted in ascending order.
  • 30. #include <iostream> using namespace std; // A utility function to get maximum value in arr[] int getMax(int arr[], int n) { int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx; }
  • 31. // A function to do counting sort of arr[] according to // the digit represented by exp. void countSort(int arr[], int n, int exp) { int output[n]; // output array int i, count[10] = {0}; // Store count of occurrences in count[] for (i = 0; i < n; i++) count[ (arr[i]/exp)%10 ]++;
  • 32. // Change count[i] so that count[i] now contains actual // position of this digit in output[] for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the output array for (i = n - 1; i >= 0; i--) { output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; count[ (arr[i]/exp)%10 ]--; }
  • 33. // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (i = 0; i < n; i++) arr[i] = output[i]; } // The main function to that sorts arr[] of size n using // Radix Sort void radixsort(int arr[], int n) {
  • 34. // Find the maximum number to know number of digits int m = getMax(arr, n); // Do counting sort for every digit. Note that instead // of passing digit number, exp is passed. exp is 10^i // where i is current digit number for (int exp = 1; m/exp > 0; exp *= 10) countSort(arr, n, exp); }
  • 35. // A utility function to print an array void print(int arr[], int n) { for (int i = 0; i < n; i++) cout << arr[i] << " "; }
  • 36. // Driver program to test above functions int main() { // arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; //int n = sizeof(arr)/sizeof(arr[0]); int n; cout << "How many numbers? "; cin >> n; int arr[n];
  • 37. cout << "Enter the numbers:n"; for (int i = 0;i < n;i++) { cout << "t"; cin >> arr[i]; } radixsort(arr, n); print(arr, n); return 0; }
  • 38. Unsorted array a = {3, 10, 9, 8, 53, 2, 62, 71}