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. Prepared by, Santosh Kabir. 5. Sorting Methods Mobile : 98336 29398 [ [email protected]]www.santoshkabirsir.com Pg.1 of 25
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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.
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++)
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++){
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){
( 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
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
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++)
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,
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
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++){
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){
// 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++)
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){
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++){