SlideShare a Scribd company logo
1 of 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}

More Related Content

What's hot

What's hot (20)

Data Structures with C Linked List
Data Structures with C Linked ListData Structures with C Linked List
Data Structures with C Linked List
 
Networking in python by Rj
Networking in python by RjNetworking in python by Rj
Networking in python by Rj
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
 
C multiple choice questions and answers pdf
C multiple choice questions and answers pdfC multiple choice questions and answers pdf
C multiple choice questions and answers pdf
 
Linked list
Linked listLinked list
Linked list
 
Computer science project work
Computer science project workComputer science project work
Computer science project work
 
Bruteforce algorithm
Bruteforce algorithmBruteforce algorithm
Bruteforce algorithm
 
Abstract data types (adt) intro to data structure part 2
Abstract data types (adt)   intro to data structure part 2Abstract data types (adt)   intro to data structure part 2
Abstract data types (adt) intro to data structure part 2
 
Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]Data Structures - Lecture 8 [Sorting Algorithms]
Data Structures - Lecture 8 [Sorting Algorithms]
 
DAA Lab File C Programs
DAA Lab File C ProgramsDAA Lab File C Programs
DAA Lab File C Programs
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
Python network programming
Python   network programmingPython   network programming
Python network programming
 
Synopsis on railway reservation system
Synopsis on railway reservation systemSynopsis on railway reservation system
Synopsis on railway reservation system
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Python tuples and Dictionary
Python   tuples and DictionaryPython   tuples and Dictionary
Python tuples and Dictionary
 
Knuth morris pratt string matching algo
Knuth morris pratt string matching algoKnuth morris pratt string matching algo
Knuth morris pratt string matching algo
 
Linked List
Linked ListLinked List
Linked List
 
Lecture 2a arrays
Lecture 2a arraysLecture 2a arrays
Lecture 2a arrays
 
ASP.NET Page Life Cycle
ASP.NET Page Life CycleASP.NET Page Life Cycle
ASP.NET Page Life Cycle
 

Similar to 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
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
saneshgamerz
 
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 to 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
 
CP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdfCP PPT_Unit IV computer programming in c.pdf
CP PPT_Unit IV computer programming in c.pdf
 
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
 

Recently uploaded

1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
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
 

Recently uploaded (20)

psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptxSKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
SKILL OF INTRODUCING THE LESSON MICRO SKILLS.pptx
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
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
 
Spatium Project Simulation student brief
Spatium Project Simulation student briefSpatium Project Simulation student brief
Spatium Project Simulation student brief
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 

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}