05 sorting methods
DESCRIPTION
Sorting techniquesTRANSCRIPT
DS - DSAA ( Common Topics )
5. Sorting Methods
Sorting means arranging a given set of data in some order. Different methods are used to arrange data in ascending and descending order. The sorting methods can be divided into two broad categories. They are as follows,
Internal sorting : If all the data that is to be sorted can be accommodated in memory then internal sorting methods are used. During the sort process the entire data (e.g. records, numbers, strings) is held in common data types like arrays, objects or derived data structures like queues, stacks.
External sorting : When the data to be sorted is very large, the data that is currently being processed is held in primary memory and some data is kept in auxiliary storage device like hard disk, floppy disk etc., external sort is used. Usually if there are thousands of records stored in a disk file then some of records are taken into memory for processing at a time.
In this chapter we will be working on the internal sorting methods. Also the methods discussed will sort the given data in ascending order (i.e. arrange the array elements from smallest value to largest value).
We will discuss some of the sorting techniques using C programs. For understanding these methods we will assume that the data to be sorted is given in the form of an array of integers. The sorting procedures will have the array to be sorted and number of elements to sort as a function parameters. For sorting, the methods go through the array or part of the array multiple times. Going once through array is called ‘One Pass’ through the array.The main() function will input the values into an array and call sorting function. Then, the main() method will display the sorted array.
Selection Sort: Note : According to the way of selecting and arranging elements, sorting methods are further classified into different types : Selection Sorts : In these methods successive elements are selected in order and placed into their proper sorted position. Given a list of elements we simply select the largest (or smallest) element and place it in sorted list. Again from the remaining unsorted list largest (or smallest) element is selected and placed in sorted list.
Method:Here in each pass the largest element is selected from a given unsorted sub list and exchanged with last element of the sub-list. e.g. given array of n elements. The method first finds largest number form n elements and places it at the end i.e. nth position. Then, a largest number is found from remaining n-1 elements and it is placed at n-1 position. Then same steps are taken for n-2 elements and in such way this is repeated for n-1 times. The array is sorted from last index.
Algo:
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.1 of 22
DS - DSAA ( Common Topics )
Inputs: List of elements ( A ), Length N
1. Initialize a variable last = N -1
2. While last is not 0, repeat following
a. Store X = A[0]
b. For index I= 1 to last
i. If Ith element is larger than X, then
1. Store X = A[ I ]
2. Store P = I
c. Swap the largest element (at index P) with element at index last
d. Decrement var. last and go to 2
3. Return sorted array.
Complete Program for Selection Sort :
#include<stdio.h>#include<conio.h>void SelectionSort( int a[ ], int n ){
int last, i, p, largest;
int k , pass=1; // for passes
for(last= n-1 ; last>0 ; last--){
// Find largest elmt and its index up to index ‘last’ largest = a[0];
p = 0; for(i=1; i<=last; i++)
{if(a[i] > largest ){
largest = a[i];p = i;
}}// Exchange last and largest elementa[p] = a[last];a[last] = largest;
// --- to print passesprintf("\nPass:%d\n" , pass );for(k=0 ; k<n; k++)
printf("%d\t" , a[k] );pass++;// ---
}}
void main( )
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.2 of 22
The portion of program in rectangle is only for displaying steps in the sorting method. Not part of actual sorting algorithm.
DS - DSAA ( Common Topics )
{int a[50];
int i , n;printf("-- SELECTION SORT METHOD --\n\n");
// I/P number of elements to be sortedprintf("Enter number of elements (max 50) :");scanf("%d", &n);// Input n numbers in arrayprintf("Enter %d nos : \n\n", n);for(i=0; i<n; i++)
scanf("%d", &a[i]);// Call sorting function. Parameters : array , nSelectionSort( a, n );// O/P the sorted arrayprintf("\n\n Sorted array ...\n");for(i=0; i<n; i++)
printf("%d\t", a[i]);
getch();}
Consider following six numbers as input :
25 15 50 30 10 40 Input
25 15 40 30 10 50
25 15 10 30 40 50
25 15 10 30 40 50
10 15 25 30 40 50
10 15 25 30 40 50 Final sorted array
Insertion Sort:Note :
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.3 of 22
These are also available at :
www.santoshkabirsir.com
DS - DSAA ( Common Topics )
Insertion Sorts: These sorting methods are implemented by inserting a particular element in a list at the appropriate position.Method:In this method the given list is always divided into to parts : sorted and unsorted. In each pass a proper place found for the element at the beginning of unsorted list and is kept in a sorted list. The beginning of the unsorted list moves further.e.g. Assume array has n elements. Then, at certain point, list is sorted from 0 to p-1. Also, p to n-1 there is unsorted list. Then we insert element a[p], at a proper position in from 0 to p. Now, 0 to p elements are sorted. Thus, we consider p = p+1. Now insert element a[p] at proper position from 0 to p. This is repeated from all p from 1 to n-1 in the array.Algorithm for the above method is as follows,Algo:
Inputs: The array of number A.
1. For index P=1 To N-1, Repeat following
a. Store element A[P] aside. T = A[P]
b. For index I = P-1 to 0 , repeat following
i. If Ith element is larger than T, then
shift A[P] to A[P+1]
ii. Else
Stop the loop
c. Store T at I+1. A[ I+1] = T
2. Return the sorted array.
void InsertionSort( int a[ ], int n ){
int p, i , temp ;int k, pass=1; // for passesfor(p=1; p< n ; p++){
temp = a[p];for( i=p-1; i>=0; i--){
if(temp >= a[i] )break;
elsea[i+1] = a[i];
}a[i +1] = temp;
// --- For printing passesprintf("\nPass %d :\n" ,pass++);for(k=0; k< n; k++)
printf("%d\t", a[k] );//-------
}}
Sorting Passes :
30 20 15 45 25 35 Input numbers
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.4 of 22
DS - DSAA ( Common Topics )
20 30 15 45 25 35
15 20 30 45 25 35
15 20 30 45 25 35
15 20 25 30 45 35
15 20 25 30 35 45 … Sorted array
Shell Sort :First designed by Donald Shell.Method : The method compares the distant elements at particular distance in the array of size N. This, distance is called as Increment, which is initially taken as N/2 (as suggested in original method by Shell). The collection of elements (located at Increment distance, on the left side from current position (Say P) are compared. And this collection is sorted. This P is incremented up to last index of array. Then, the Increment is reduced to half of its current value till 1. Again P is initialized to Increment value and same procedure is repeated. The last value of Increment considered will be 1.
Algo : ShellSort.
Input : Array A of integers, no. of elements N
1. Set incr = N/2
2. While incr >= 1, repeat following
a. For J = incr To N
i. Set Temp = A[ J ]
ii. For I=J-incr To 0
If Temp < A[ I ] Then
A[ I + incr ] = A[ I ]
Else
Stop this Loop
iii. Set A[ I + incr ] = Temp
b. Set incr = incr /2 and jump to Step 2
3. Return sorted array.
Function for Shell Sort :void ShellSort(int a[],int n){
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.5 of 22
DS - DSAA ( Common Topics )
int j, i, incr, temp; int k; // for passes for( incr = n/2; incr>0; incr/=2) {
for( j = incr; j< n; j++){
temp = a[j];for( i= j-incr; i>=0; i-= incr ){
if( temp < a[i] ) a[i+incr] = a[i]; else break;
} a[i+incr] = temp;
} // display passes.. printf("\nIncr.:%d\n", incr); for(k=0; k<n; k++ ) printf("%d\t", a[k] );
}}
Sorting Passes :
30 15 70 50 60 35 25 40 Input numbers
30 15 25 40 60 35 70 50 Incr.: 4
25 15 30 35 60 40 70 50 Incr.: 2
15 25 30 35 40 50 60 70 Incr.: 1
Quick Sort :
( Type : Exchange sort )Method: It’s a very popular method and one of the fastest methods, too. The method uses the fact that it is easier and faster to sort two small arrays than to sort one larger array. The method works in following way.The method picks any element (called pivot) from the list and puts it into the position such that it will be its position in the final sorted array. Also, while doing this, elements smaller (or equal) to pivot element are transferred on the left of pivot and all the larger elements on the right of the pivot. Now, the original list is
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.6 of 22
DS - DSAA ( Common Topics )
divided (logically) into two lists at the pivot and above steps are repeated for the two lists (i.e. for the elements on the left and right of the pivot). Selection of pivot element can be at random. But, for simplicity of program and understanding we will consider the first element in the list for pivot. There are different methods of selecting pivot.
QuickSort – Recursive procedureAlgo:
Inputs: Array of int : A
Lower and upper bounds of the list to be sorted
If difference between bounds is > 1 then
Get the partition position for sub-array. (Invoke Partition Algo.)
Apply quick sort for left partition
Apply quick sort for right partition
Algo. For Partition procedure
Input: An array, and lower and upper bound for part of the array to partition
Initialize two counters: at lower bound (say l), and upper bound (say u)
Store the element at lower bound aside
Increment counter l till bigger number is found
Decrement counter u, till smaller number is found
If l < u then
Interchange values at l and u
Else
Interchange values at lower bound and value at u
Return partition position i.e. value of u
Program for Quick Sort :#include<stdio.h>#include<conio.h>int n; // no. of elements to sortint Partition(int a[], int lb,int ub){
int no, l, u, temp;static int pass =1, k; // for passes
no = a[lb]; // Read value at lower bound i.e. First elementu = ub; // Upper boundl = lb; // Lower bound
while(l < u){
while( a[ l ] <= no && l < u ) //Move to end till smaller elements are
foundl++;
while( a[ u ] > no ) // Move towards beginning till bigger elements are
foundu--;
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.7 of 22
DS - DSAA ( Common Topics )
if(l < u ) // Interchange values at upper and lower pointers.{
temp = a[l];a[ l ] = a[ u ];a[ u ] = temp;
}
/*printf("\n");for(k=lb; k<=ub; k)
printf("%d\t" , a[k]);printf("\n");
*/}a[lb] = a[u];a[u] = no;
// passesprintf("\nPass...%d , LB=%d, UB=%d\n", pass++ , lb, ub);
for(k=0; k<n; k++)printf("%d\t", a[k] );
return (u);}void QuickSort(int a[], int lbound, int ubound){
int p; //Partition position.
if(ubound > lbound){
// Find position of partitioning element// for a sub-array given by bounds: lbound and ubound.p= Partition(a, lbound, ubound);QuickSort(a, lbound, p-1); // Call quicksort to sort left part of arrayQuickSort(a, p+1, ubound); // Call quicksort to sort right part of an array
}}
void main( ){
int a[50]; int i ;
printf("-- QUICKSORT SORT METHOD --\n\n");printf("Enter number of elements (max 50) :");scanf("%d", &n);printf("Enter %d nos : \n\n", n);for(i=0; i<n; i++)
scanf("%d", &a[i]);
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.8 of 22
DS - DSAA ( Common Topics )
// Call sorting function // Parameters : array , LowerBound=0, upperbound i.e. n-1
QuickSort( a, 0, n-1 );printf("\n\n Sorted array ...\n");for(i=0; i<n; i++)
printf("%d\t", a[i]); getch();}
Sorting Passes :30 20 60 15 25 50 Input
15 20 25 30 60 50 … For LB=0, UB=5
15 20 25 30 60 50 … For LB=0, UB=2
15 20 25 30 60 50 … For LB=1, UB=2
15 20 25 30 50 60 … For LB=4, UB=5
15 20 25 30 50 60 … Sorted Array
Bigger example for detailed understanding :50 30 90 15 80 40 85 20 75 60 Input
Pass...1 , LB=0, UB=940 30 20 15 50 80 85 90 75 60
Pass...2 , LB=0, UB=315 30 20 40 50 80 85 90 75 60
Pass...3 , LB=0, UB=215 30 20 40 50 80 85 90 75 60
Pass...4 , LB=1, UB=215 20 30 40 50 80 85 90 75 60
Pass...5 , LB=5, UB=915 20 30 40 50 75 60 80 90 85
Pass...6 , LB=5, UB=615 20 30 40 50 60 75 80 90 85
Pass...7 , LB=8, UB=915 20 30 40 50 60 75 80 85 90 Sorted array ...
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.9 of 22
DS - DSAA ( Common Topics )
15 20 30 40 50 60 75 80 85 90
Heap Sort :Type : Selection sortWhat is heap – Heap is a complete or nearly complete binary tree. It can be of two types Max-heap or Min-heap. In Max-heap a key value in each node is greater than or equal to the key values in its sub-trees. The heap can be implemented with an array as follows.Consider a three-level heap as follows,
Position of a parent (father node) F for a child node (son) at S, can be given by,F = (S-1) / 2 … the division sign (/) denoting integer division.
Thus, father of node 6 is at position 3 is, given by following exampleF = (3-1) / 2 = 2 /2 = 1
Method: It builds a heap by adjusting the positions of elements of the given list. The heapsort method involves two phases for sorting a given list. They are as follows,
1. Construct a max-heap by adjusting the array elements. ( Called as ‘Heapify’ )
2. Repeatedly eliminate the root element (largest element) of the heap by shifting it to the end of the array and then restore the heap structure ( Heapify ) with the remaining elements.
Algo:Inputs: List of elements ( int list[ ] )
1. Create a in-place max-heap from the elements in the given array
2. Swap the first element with the last element. i.e. keep the largest element at the last
position in un-sorted array.
3. Readjust the heap, up to last-1 elements, so that the array represents a max-heap up
to last-1 index.
4. Decrement the last index and repeat steps 2 and 3 till last is larger than 0.
5. Return the sorted array.
Functions for ‘Heapify’ part and Heap Sort method are given below,
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
0 1 2 3 4
44 18 23 6 10
Pg.10 of 22
44
18 23
6 10 The above tree can be represented by array as follows,
DS - DSAA ( Common Topics )
void MakeHeap(int a[] , int n) // Creating max-heap of n elements{
int val, pos,f,s,i;for(pos=1; pos<n; pos++){
val = a[pos];s = pos;f = (s-1)/2;while( s >= 1 ){
if( a[f] < val ){
a[s] = a[f];s = f;f = (s-1)/2;
}else
break;}a[s] = val;
}}void HeapSort( int a[], int n ){
int last, t;int k; // for passes
// Creates initial heap of all elements in arrayprintf("Heap creation.....\n");MakeHeap( a, n );
// --- for printing passesfor(k=0; k<n; k++)
printf("%d\t" , a[k]);printf("\n");// ---
printf("\n\nSorting ...\n");for(last= n-1; last>0; last--){
t = a[last];a[last] = a[0];a[0] = t;MakeHeap(a, last); // make heap up to last-1 elements
// --- for printing passesfor(k=0; k<n; k++)
printf("%d\t" , a[k]);printf("\n");// ---
}
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.11 of 22
DS - DSAA ( Common Topics )
}Consider following input :
50 60 30 70 65 45 Input
Then, Heap creation will be as follows,
50 60 30 70 65 45 … pos =1 ( 60 adjusted )
60 50 30 70 65 45 … pos =2 (No change ) Max heap up to pos=1
60 50 30 70 65 45 …pos =3 (70 adjusted) Max heap up to pos=2
70 60 30 50 65 45 … pos=4 (65 adjusted) Max heap up to pos=3
70 65 30 50 60 45 …pos=5 (45 adjusted) Max heap up to pos=4
70 65 45 50 60 30 … Max heap up to pos=5 ( Final Max heap )
Following figure shows Max heap creation : ( In Tree format )
Original array:
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.12 of 22
1 2
3 45
0 50
30
60
65
70
45
1 2
3 45
0 70
30
60
65
50
45
1 2
3 45
0 60
30
50
65
70
45
pos=1 .. 60 adjusted
pos=2 .. No changes
1 2
3 45
0 60
30
50
65
70
45
pos=3 .. 70 adjusted
DS - DSAA ( Common Topics )
Steps in Sorting the array using above Max-heap :
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
65 60 45 30 50 70
60 50 45 30 65 70
Pg.13 of 22
1 2
3 45
0 70
30
65
60
50
45
pos=4 .. 65 adjusted pos=5 .. 45 adjusted
1 2
3 45
0 70
45
65
60
50
30
Final Max-Heap
Max-Heap Creation
A[0] and A[5] interchanged…Max-Heap adjusted up to index .. 4
1 2
3 45
0 65
45
60
50
30
70
A[0] and A[4] interchanged…Max-Heap adjusted up to index .. 3
1 2
3 45
0 60
45
50
65
30
70
A[0] and A[3] interchanged…Max-Heap adjusted up to index .. 2 1 2
3 45
0 50
45
30
65
60
70
These are also available at :
www.santoshkabirsir.com
DS - DSAA ( Common Topics )
Merge Sort:Concept behind the method:Merge sort uses concepts of merging two sorted arrays into the third one using particular algorithm such that the merged array is a sorted array. Following procedure shows process of merging two sorted arrays,
Method: The technique of merging two sorted lists into third list (which is a sorted list) can be used to sort a single array in a following way. Consider an array of size n. Assume the array is made up of n sub-arrays each of size 1 and merge adjacent pairs of the list. Since, an array of size one is always in sorted form, by applying the above procedure on the two, we get multiple sorted arrays of each of size two. Then, we will consider n/2 arrays each of size 2 and merge them to form multiple sorted arrays of size 4. Repeat this process until there is only one array of size n.
Algo:Inputs: Array of numbers A, Number of elements to sort N.
1. Consider a variable ‘Size’ as 1
2. While size is less than N repeat following
a. Sub divide the array into multiple arrays of length= size
b. Initialize Lower bound L1=0,
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
50 30 45 60 65 70
45 30 50 60 65 70
30 45 50 60 65 70
Pg.14 of 22
A[0] and A[2] interchanged…Max-Heap adjusted up to index .. 1 1 2
3 45
0 45
50
30
65
60
70
A[0] and A[1] interchanged…Max-Heap adjusted up to index .. 1
And entire array is sorted .1 2
3 45
0 45
50
30
65
60
70
Final Sorted Array
DS - DSAA ( Common Topics )
c. Set Index for resultant array K=0
d. While Pairs are available, do
i. Get lower ( L2) and upper bounds (U1,U2) of two parts to merge
ii. Set I=L1, J=L2
iii. While not end of any of the parts
1. If A[I] < A[J] then
a. B[K] = A[I]
b. I = I+1
2. Else
a. B[K] = A[J]
b. J = J+1
3. K = K+1
iv. Get new L1, and go to 2.d
e. Copy remaining array A (from K to n-1) into B
f. Copy entire array B to original Array A
g. Double the Size, go to step 2
3. Return sorted array
Non-recursive Function :
void MergeSort( int a[], int n ){
// create an auxuliary array (of same size n) for processingint b[50];int i,j,k, l1,l2, u1,u2, size;int pass=1; // for passessize = 1; // Initial block sizewhile(size < n) // Stop if block size exceeds list size{
l1 = 0; // Initial lower lim. for first blockk = 0; // Initialize start index aux array to 0while(l1+size <n) // Stop if new blocks can't be be formed{
// decide the upper and lower lim of the blocku1 = l1 +size -1;l2 = u1 + 1;
// Upper lim of second block should be less than list lim.u2 = l2+size < n ? l2+size-1 : n-1;
// Merge two blocks: with l1 .. u1 and l2 .. u2for(i=l1, j=l2; i<=u1 && j<=u2; k++){
if(a[i] <= a[j]){
b[k] = a[i];i++;
}
else
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.15 of 22
DS - DSAA ( Common Topics )
{b[k] = a[j];j++;
}}
// merge array endswhile( i<= u1 )
b[k++] = a[i++];while( j<= u2 )
b[k++] = a[j++];l1 = u2 + 1; // new lower lim of first block
}// Copy remaining values in aux. arraywhile( k < n ){
b[k] = a[k];k++;
}// Copy the aux. array back into original array for next passfor(i=0; i<n; i++)
a[i] = b[i];
//adjust the size of blocks (sub-arrays) for next passsize *= 2;
// --- for printing passesprintf("\nPass:%d\n" , pass++); for(i=0; i<n; i++)
printf("%d\t", a[i] );printf("\n");// ---
}}
Sorting passes for 7 numbers is shown below,
50 20 40 70 80 60 30 Input
50 20 40 70 80 60 30 … Merge parts of size 1
20 50 40 70 60 80 30 … Merge parts of size 2 (or less )
20 40 50 70 30 60 80 … Merge parts of size 4 (or less)
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.16 of 22
DS - DSAA ( Common Topics )
20 30 40 50 60 70 80 … Final sorted array
Recursive Merge-Sort:In the recursive merge sort method the Merge array procedure is invoked through the merge sort procedure for different parts of the array. Mergesort calls itself recursively for left and right half of the array.
Program for Recursive Merge Sort :
int n; // for number of elements to sort
int pass=1; // for counting passes
void MergeArray(int a[],int lb,int mid, int ub){
int i,j,k=lb;int b[50];i=lb;j=mid+1;while((i<=mid)&&(j<=ub)){
if(a[i]<a[j])b[k]=a[i++];
elseb[k]=a[j++];
k++;}if(i>mid){
while(j<=ub)b[k++] = a[j++];
}else{
while(i<=mid)b[k++ ]=a[i++ ];
}for(i=lb; i<=ub; i++)
a[i] = b[i];}void MergeSort(int a[], int lb, int ub){
int mid,i;if(lb<ub){
mid=(lb+ub)/2;MergeSort(a, lb, mid);MergeSort(a, mid+1, ub);MergeArray(a, lb, mid, ub);
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.17 of 22
DS - DSAA ( Common Topics )
// printing passes can be done hereprintf("\nPass...%d, LB=%d, UB=%d\n", pass, lb, ub );for(i=0;i< n;i++)
printf( "%d\t" , a[i]);pass++;printf("\n");
}}void main( ){
int a[50]; int i;
printf("—RECURSIVE MERGE SORT METHOD --\n\n");printf("Enter number of elements (max 50) :");scanf("%d", &n);printf("Enter %d nos : \n\n", n);for(i=0; i<n; i++)
scanf("%d", &a[i]);
// Call sorting function // Parameters : array , LB, UB
MergeSort( a, 0 , n-1 );
getch();}
Following Sorting steps are shown for 7 numbers :
50 20 40 70 80 60 30 Input
20 50 40 70 80 60 30 … Pass...1, LB=0, UB=1
20 50 40 70 80 60 30 … Pass...2, LB=2, UB=3
20 40 50 70 80 60 30 … Pass...3, LB=0, UB=3
20 40 50 70 60 80 30 … Pass...4, LB=4, UB=5
20 40 50 70 30 60 80 … Pass...5, LB=4, UB=6
20 30 40 50 60 70 80 … Pass...6, LB=0, UB=6
20 30 40 50 60 70 80 … Sorted array
Radix Sort :
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.18 of 22
DS - DSAA ( Common Topics )
Method : The method is suitable for the data in the form of integers. It rearranges the numbers multiple times bases on value of each of the digits in the numbers. It first sorts the numbers based on Least Significant Digits(LSD), then sorts the numbers with second LSD and so on till Most significant Digit.
For sorting numbers on each digit it maintains 10 linked (for 10 digits), called as buckets. The method fills up the buckets with the numbers according their LSD first. Then it empties all the buckets back into original array. Same process is repeated for next digits till MSD of largest number.
Functions for Radix Sort and Working with buckets (i.e. linked lists )
// --- Code for making linked list ---struct Node{
int no; struct Node *next;
};struct Node *bukt[10]; // array of 10 buckets(10 linked lists)
// Add node to ith bucketvoid AddElement(int v, int i){
struct Node *temp = (struct Node*)malloc(sizeof(struct Node) );temp->no = v;
temp->next = NULL;
if( bukt[i]== NULL )bukt[i] = temp;
else{
struct Node *q = bukt[ i ];while( q->next != NULL )
q = q->next;
q->next = temp ;}
}// To remove node from a ith bucket.. del first node of ith Linked listint RemoveElement( int i ){
int v = bukt[i]->no;bukt[i] = bukt[i]->next;return v;
}// --- code for linked list ends ----
void RadixSort( int a[], int n)
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.19 of 22
DS - DSAA ( Common Topics )
{int i,j,k,e=1;//Assuming max. 3 dig. nosfor(k=1; k<=3; k++){
// Initialize the buckets (as empty).for(i=0; i<10; i++)
bukt[i] = NULL;
for( i=0; i< n; i++ ){
// Separate the kth digitj = (a[i]/e) % 10;// Store the no. in proper bucketAddElement( a[i] , j);
}
// Copy Bucket contents into original arrayj =0;for(i=0; i<10; i++){
while( bukt[i] != NULL ){
a[j] = RemoveElement( i );j++;
}}e = e*10;
// display passes printf("\n\n"); for( i=0; i<n; i++ ) printf("%d\t", a[i] ); //------
}}
Sorting Passes :
563 450 703 245 275 221 107 353 Input
450 221 563 703 353 245 275 107 … Sorted based on LSD
703 107 221 245 450 353 563 275 … Sorted based on Second digit
107 221 245 275 353 450 563 703 … Sorted based on MSD
107 221 245 275 353 450 563 703 … Sorted array
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.20 of 22
DS - DSAA ( Common Topics )
Bucket Sort :
Method : The method is efficient for sorting list integers with smaller values. The method starts by first finding the largest number (L) in given array A.Then, it creates a temporary array of integers (say T) of length = L +1.All elements in the T array is initially filled with zeros.Then the method goes though the given array elements and increments the contents of temporary array according to the current number in the array A.
e.g. A[I] is 7 then it increments value T[7] i.e. T[ A[I] ] by one. In this process, the counts at some of the indexes in T array will increment. e.g. in the given list number 4 is not their then T[4] will remain 0.The method then goes through T array and wherever count >0, is found those indexes are stored in the original array. Here, we get a sorted array.
void BucketSort(int a[], int n ){
int i, j, c, max; int *b;
// get the largest no. in the arraymax = a[0];for(i=1; i< n; i++)
if( a[i] > max)max = a[i];
// allocate array (bucket array) of size= largest no +1b = (int*) calloc( max+1, sizeof(int) );//Put the numbers from original array into proper bucketfor(i=0; i<n; i++)
b[ a[i] ]++;// copy bucket array to original array only for existing numbers i.e. count>=1j=0;for(i=0; i<=max; i++){
if( b[i] > 0 ) { for( c=1; c<=b[i]; c++ ) a[j++] = i; } }}
Sorting and Condition of Bucket array is shown below,
4 3 8 4 9 2 6 Input
Largest Number in given array is 9.Temporary array ( b ) of size 9+1 i.e. 10 createdArray b holds count of the numbers present in original array
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
Pg.21 of 22
DS - DSAA ( Common Topics )
Bucket array
2 3 4 4 6 8 9 … Sorted array
-----000-----
Prepared by, Santosh Kabir. 5. Sorting MethodsMobile : 98336 29398 [ [email protected]] www.santoshkabirsir.com
b 0 1 2 3 4 5 6 7 8 9
0 0 1 1 2 0 1 0 1 1
Pg.22 of 22
Sem IV - IT
Web Programming ( WP )[ HTML, ASP.Net with C#, PHP, JSP, MySQL etc. ]
( Learn to design and develop small Internet based programs )
Sem II – FESPA
[ Computer Programming with C ]
Regular Batches at Andheri, Dadar, Thane
Santosh Kabir sirMobile : 98336 29398
www.santoshkabirsir.com