Sunteți pe pagina 1din 23

DATA STRUCTURES

UNIT-4

Introduction to sorting:

Sorting can be referred as a process of arranging the elements in an ordered manner. Sorting arranges data in a
sequence which makes searching easier.

Sorting is one of the methods in the concept of data structure which can be used to deal with the data in a good
and efficient manner.

Every record which is going to be sorted will contain one key. Based on the key the record will be sorted. For
example, suppose we have a record of students, every such record will have the following data:

o Roll No.

o Name

o Age

o Class

Here Student roll no. can be taken as key for sorting the records in ascending or descending order. Now suppose
we have to search a Student with roll no. 15, we don't need to search the complete record we will simply search between
the Students with roll no. 10 to 20.

Sorting classification:

The concept of sorting can be classified into two ways they are ascending order and descending order.

Ascending order means arranging of the elements from smallest value to largest value.

Example:

25 2 21 5 7 1 (UN ordered list)

1 2 5 7 21 25 (Ascending order)

25 21 7 5 2 1 (Descending order)

Descending order means arranging of the elements from largest value to smallest value.

Sorting techniques:

There are many types of sorting techniques, in which each one will follow different procedures.
Following are some sorting techniques which we will be covering in next sections.

1. Bubble Sort

Bit Institute Of Technology, Hindupur. Page 1


DATA STRUCTURES

2. Insertion Sort(straight insertion sort, list insertion sort, binary insertion sort)

3. Selection Sort

4. Quick Sort

5. Merge Sort

6. Heap Sort

7. Shell sort

8. External sort

Bubble sort:

Contents regarding bubble sort is (example prepare from notebook).

1. definition and procedure,


2. algorithm,
3. Coding sample output.

Definition:

Bubble sort is a simple sorting algorithm.


This sorting algorithm is comparison-based algorithm in which each pair of adjacent elements is
compared and the elements are swapped if they are not in order.
Sorting refers to the operation of rearranging the element.
Bubble sort algorithm requires n-1 passes, where n is the number of input items.
Here is the c program for bubble sort. The bubble sort gets its name because elements tend to
move up into the correct order like bubbles rising to the surface.
This algorithm is not suitable for large data sets as its average and worst case complexity are of (n 2)
where n is the number of items.

Bit Institute Of Technology, Hindupur. Page 2


DATA STRUCTURES

Program:

#include<stdio.h>
#include<conio.h>

int main( )
{
int a[100];
int i, j, temp, n ;
printf("how many numbers you want to sort : \n");
scanf("%d",&n);
printf("Enter %d number values you want to sort\n", n);
for(j=0; j<n; j++)
scanf("%d",&a[j]);

for(j=1;j<n;j++)
{
for(i=0; i<n; i++)
{
if(a[i]>a[i+1])
{
temp=a[i];
a[i]=a[i+1];
a[i+1]=temp;
}
}
}

printf ( "\n\nArray after sorting:\n") ;

for ( i = 0 ; i <n ; i++ )


printf ( "%d\t", a[i] ) ;
getch();
}

Bit Institute Of Technology, Hindupur. Page 3


DATA STRUCTURES

Output:

selection sort:

Contents regarding bubble sort is (example prepare from notebook).

1. definition and procedure,


2. algorithm,
3. Coding sample output.

Definition:

Selection Sort algorithm is used to arrange a list of elements in a particular order (Ascending or
Descending).
Selection sorting is conceptually the simplest sorting algorithm.
This algorithm first finds the smallest element in the array and exchanges it with the element in the first position.
Then find the second smallest element and exchange it with the element in the second position, and continues in
this way until the entire array is sorted.
In selection sort, the first element in the list is selected and it is compared repeatedly with
remaining all the elements in the list.

Bit Institute Of Technology, Hindupur. Page 4


DATA STRUCTURES

Selection Sort is a simple-unstable-in-place Sorting Algorithm. Selection sort is efficient when


memory is limited and over a small set of data, while make it more complex and inefficient
on large set of data and become more worse

Note:

The above Selection sort, described uses swapping of data which makes the algorithm Unstable,
while Selection sort can also be implemented as Stable sort, by selecting the smallest element and putting
the element before the first element of the list i.e. instead of swapping the first element with the smallest
element, we are sweeping the first element to second position, second to third and so on.

Let us consider values :


3 6 1 8 4 5

(Or)

Selecting the first smallest and swapping

Selecting Second smallest from the list and comparing with the second position

Bit Institute Of Technology, Hindupur. Page 5


DATA STRUCTURES

Selecting the third element and comparing with the remaining element and swapping

Already sorted

Sorted: C program for Selection Sort

Code:

#include <stdio.h>

//Selection Sort function to Sort Integer array list


int *selectionSort(int array[],int n)
{
int j,temp,i;

//Iterate start from first element


for (i = 0; i < n; i++)
{
//Iterate and compare till it satisfies condition
for(j = i+1; j < n; j++)
{
if(array[i] > array[j])
{//Swaping operation
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
//return Sorted array
return array;
}

void main()
{
//declaring variables
int array[1000],n,i;

//Number of elements in array form user input


printf("Enter the number of element you want to Sort : ");
scanf("%d",&n);

//code to ask to enter elements from user equal to n

Bit Institute Of Technology, Hindupur. Page 6


DATA STRUCTURES
printf("Enter Elements in the list : ");
for(i = 0; i < n; i++)
{
scanf("%d",&array[i]);
}

//calling selectionSort function defined above and gettting


//sorted array in sortArray variable
int *sortArray = selectionSort(array,n);

//print sorted array


printf("Sorted list : ");
for(i = 0; i < n; i++ )
{
printf("%d\t",sortArray[i]);
}
}
Output:

Insertion sort:

The procedure compare first and second values and put them in order or correct position by
inserting, now take out third one and compare it with second and first and put it in right position.
Now take out fourth and so on. This approach of inserting element in a sorted list is called
as Insertion sort.
C program for Insertion Sort. Insertion sort is one of the simple-stable-in places Sorting
Algorithm which is efficient when applied over small set of data.
While insertion sort takes more time to perform sorting over large list i.e less efficient for large
set of data, as compare to other sorting algorithm.

The insertion sort algorithm is performed using following steps...

Step 1: Assume that first element in the list is in sorted portion of the list and remaining all elements are
in unsorted portion.

Bit Institute Of Technology, Hindupur. Page 7


DATA STRUCTURES

Step 2: Consider first element from the unsorted list and insert that element into the sorted list in order
specified.

Step 3: Repeat the above process until all the elements from the unsorted list are moved into the sorted
list.

Example

Bit Institute Of Technology, Hindupur. Page 8


DATA STRUCTURES

Bit Institute Of Technology, Hindupur. Page 9


DATA STRUCTURES

Here is the source code:


#include<stdio.h>
#include<conio.h>

void main(){

int size, i, j, temp, list[100];

printf("Enter the size of the list: ");


scanf("%d", &size);

printf("Enter %d integer values: ", size);


for (i = 0; i < size; i++)
scanf("%d", &list[i]);

//Insertion sort logic


for (i = 1; i < size; i++) {
temp = list[i];
j = i - 1;
while ((temp < list[j]) && (j >= 0)) {
list[j + 1] = list[j];
j = j - 1;
}
list[j + 1] = temp;
}

printf("List after Sorting is: ");


for (i = 0; i < size; i++)
printf(" %d", list[i]);

getch();
}

Output:

Enter size of the list

Enter 6 integer values

5 6 3 1 2 4

List after sorting

1 2 3 4 5 6

Bit Institute Of Technology, Hindupur. Page 10


DATA STRUCTURES

Linked List in C Insertion Sort:

Source Code:
#include<stdio.h>
struct node
{
int data;
struct node *next;
};

struct node *head=NULL;

void insert_sort(int data)


{
struct node *temp=head;
struct node *prev=NULL;
struct node *ptr;

ptr=(struct node*)malloc(sizeof(struct node));


ptr->data=data;
ptr->next=NULL;

if(temp==NULL)
{
//Executes when linked list is empty
ptr->next=NULL;
head=ptr;
return;
}

if(data<temp->data)
{
//Executes if given data is less than data in first node of linked list
ptr->next=head;
head=ptr;
return;
}
else
{
while(temp!=NULL)
{
if(data>temp->data)
{
//Traverse to location we want to insert the node + 1 node
prev=temp;
temp=temp->next;
continue;
}
else
{
//Insert the node
prev->next=ptr;
ptr->next=temp;

Bit Institute Of Technology, Hindupur. Page 11


DATA STRUCTURES
return;
}
}
prev->next=ptr;
//Insert node at last
}
}

void print()
{
struct node *temp=head;
printf("\nList:");
while(temp!=NULL)
{
printf("\n%d ",temp->data);
temp=temp->next;
}
}
int main()
{
insert_sort(23);
print();

insert_sort(10);
print();

insert_sort(15);
print();

insert_sort(45);
print();

insert_sort(50);
print();

return 0;
}
Output:
List:
23

List:
10 23

List:
10 15 23

List:
10 15 23 45

List:
10 15 23 45 50
Quick sort:
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays.

Bit Institute Of Technology, Hindupur. Page 12


DATA STRUCTURES

A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based
on which the partition is made and another array holds values greater than the pivot value.
It comes under divide and conquer algorithm which divides the large set of array in small by picking up a pivot
element as a reference element, and do sorting.

Quick Sort Algorithm:

1. If n < = 1, then return.


2. Pick any element V in a[]. This is called the pivot.
3. Rearrange elements of the array by moving all elements xi > V right of V and all elements xi < = V left of V. If the place of the V after
re-arrangement is j, all elements with value less than V, appear in a[0], a[1] . . . . a[j 1] and all those with value greater than V appear in
a[j + 1] . . . . a[n 1].
4. Apply quick sort recursively to a[0] . . . . a[j 1] and to a[j + 1] . . . . a[n 1].

Example need to prepare from notebook whatever we discussed.


Program:

#include <stdio.h>

void quick_sort(int[],int,int);
int partition(int[],int,int);

int main()
{
int a[50],n,i;
printf("How many elements?");
scanf("%d",&n);
printf("\nEnter array elements:");

for(i=0;i<n;i++)
scanf("%d",&a[i]);

quick_sort(a,0,n-1);
printf("\nArray after sorting:");

for(i=0;i<n;i++)
printf("%d ",a[i]);

return 0;
}

void quick_sort(int a[],int l,int u)


{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}

int partition(int a[],int l,int u)


{
int v,i,j,temp;

Bit Institute Of Technology, Hindupur. Page 13


DATA STRUCTURES
v=a[l];
i=l;
j=u+1;

do
{
do
i++;

while(a[i]<v&&i<=u);

do
j--;
while(v<a[j]);

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);

a[l]=a[j];
a[j]=v;

return (j);
}

Output:

Merge sort:

Bit Institute Of Technology, Hindupur. Page 14


DATA STRUCTURES

Merge sort is a sorting technique based on divide and conquer technique.


It is very efficient sorting algorithm with near optimal number of comparison.
Recursive algorithm used for merge sort comes under the category of divide and conquer technique.
An array of n elements is split around its center producing two smaller arrays.
After these two arrays are sorted independently, they can be merged to produce the final sorted array.
The process of splitting and merging can be carried recursively till there is only one element in the array. An array with 1
element is always sorted.

An example of merge sort in C is given below. First divide the list into the smallest unit (1 element), then
compare each element with the adjacent list to sort and merge the two adjacent lists. Finally all the elements are
sorted and merged.

Program for merge sort:


#include<stdio.h>

Bit Institute Of Technology, Hindupur. Page 15


DATA STRUCTURES

void mergesort(int a[],int i,int j);


void merge(int a[],int i1,int j1,int i2,int j2);

int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");

for(i=0;i<n;i++)
scanf("%d",&a[i]);

mergesort(a,0,n-1);

printf("\nSorted array is :");


for(i=0;i<n;i++)
printf("%d ",a[i]);

return 0;
}

void mergesort(int a[],int i,int j)


{
int mid;

if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}

void merge(int a[],int i1,int j1,int i2,int j2)


{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;

while(i<=j1 && j<=j2) //while elements in both lists


{
if(a[i]<a[j])
temp[k++]=a[i++];
else
temp[k++]=a[j++];
}

while(i<=j1) //copy remaining elements of the first list


temp[k++]=a[i++];

while(j<=j2) //copy remaining elements of the second list


temp[k++]=a[j++];

//Transfer elements from temp[] back to a[]


for(i=i1,j=0;i<=j2;i++,j++)
a[i]=temp[j];

Bit Institute Of Technology, Hindupur. Page 16


DATA STRUCTURES
}

Output:

Shell sort:
Shell sorting was first introduced by Donald Shell.
It generalized as exchanging sort, such as bubble or insertion sorting, by allowing the comparison and exchange of
elements that lie far apart.
The running time of Shell sort is heavily dependent on the gap sequence it uses.
For many practical variants, determining their time complexity remains an open problem.

Steps for solution of shell sorting:

step.1:
Set up a inc number. inc number is set according to given elements in the list.

step.2:
mark each elements which is comes in inc element.
For example, if list contains 10 elements then and we assume inc is 3 then, marking of elements such as next marking element,
add last element +3 to get next element and so on. Then marking element would be 1st element, 4th element(add 3), 7th
element(add 3), 10th element.

89 46 99 12 33 14 69 41 33 28

1 2 3 4 5 6 7 8 9 10 [index number]

step.3:
sort marking elements such as smallest to greater is set as left to right and not change remain element.
For example, we apply this step in above example:

12 46 99 28 33 14 69 41 33 89

step.4:
reduce inc number to one i.e. if inc number is earlier is 3 then now it would be 3-1 = 2.

step.5:
Repeat step 2,3 and 4 till all the elements not sorted.

Let's understand shell sorting using example:

35 12 14 9 15 45 32 95 40 5
//assume inc=3
//Now marking 1st element, 1+3=4th element, //4+3=7th element, 7+3=10th element

35 12 14 9 15 45 32 95 40 5
//step-3 i.e. sorting of marked elements

Bit Institute Of Technology, Hindupur. Page 17


DATA STRUCTURES
5 12 14 9 15 45 32 95 40 35
//now inc=3-1=2
//new marking is 1st element, 1+2=3th element, //3+2=5 element, 5+2=7th element, 7+2=9th //element

5 12 14 9 15 45 32 95 40 35
//now sorting of marked elements

5 12 14 9 15 45 32 95 40 35
//Now inc=2-1=1
//Now every elements all marked because inc=1

5 12 14 9 15 45 32 95 40 35
//sorting of marked elements

5 9 12 14 15 32 35 40 45 95

Program for shell sort:


#include<stdio.h>
void ShellSort(int a[], int n)
{
int i, j, increment, tmp;
for(increment = n/2; increment > 0; increment /= 2)
{
for(i = increment; i < n; i++)
{
tmp = a[i];
for(j = i; j >= increment; j -= increment)
{
if(tmp < a[j-increment])
a[j] = a[j-increment];
else
break;
}
a[j] = tmp;
}
}
}

int main()
{
int i, n, a[10];
printf("Enter the number of elements :: ");
scanf("%d",&n);
printf("Enter the elements :: ");
for(i = 0; i < n; i++)
{
scanf("%d",&a[i]);

Bit Institute Of Technology, Hindupur. Page 18


DATA STRUCTURES

}
ShellSort(a,n);
printf("The sorted elements are :: ");
for(i = 0; i < n; i++)
printf("%d ",a[i]);
printf("\n");
return 0;
}

OUTPUT:
Enter the number of elements: 6
Enter the elements: 50 30 10 40 20 60
The sorted elements are: 10 20 30 40 50 60

Bit Institute Of Technology, Hindupur. Page 19


DATA STRUCTURES
Heap sort:
Data structures using C, Heap sort algorithm starts by building a heap from the given elements, and then heap removes
its largest element from the end of partially sorted array.
After removing the largest element, it reconstructs the heap, removes the largest remaining item, and places it in the
next open position from the end of the partially sorted array.
This is repeated until there are no items left in the heap and the sorted array is full.
Elementary implementations require two arrays one to hold the heap and the other to hold the sorted elements.
Initially to implement heap sort we need to construct heap tree and we need consider either which order need to
implement
Which means either ascending order or descending order
For ascending order we need to construct minimum heap tree and maximum heap tree for descending order.
Minimum heap tree means root node must be small when comparing with the remaining node values of a tree.
Maximum heap tree means root node must be big value when comparing with the remaining node values of a tree.

Steps to implement heap sort:

Unsorted elements
45 33 3 17 25 80

Heap sort steps:


1. Construct heap tree
a. Ascending order-minimum heap tree
b. Descending order-maximum heap tree
2. Delete root node and replace it with last node of a tree
3. Heapify tree(which means reconstruction of tree because after first step the tree must and should t
become and not satisfying either minimum or maximum heap so based on our order we need to heapify
the tree).
4. Repeat step 2 and step 3 until heap tree remained with single element.

Maximum heap tree:

80

33 45

17 25
3
Program for heap tree:
#include<stdio.h>
void heapsort(int[],int);
void heapify(int[],int);
void adjust(int[],int);
main() {
int n,i,a[50];
system("clear");
printf("\nEnter the limit:");
scanf("%d",&n);
printf("\nEnter the elements:");

Bit Institute Of Technology, Hindupur. Page 20


DATA STRUCTURES
for (i=0;i<n;i++)
scanf("%d",&a[i]);
heapsort(a,n);
printf("\nThe Sorted Elements Are:\n");
for (i=0;i<n;i++)
printf("\t%d",a[i]);
printf("\n");
}
void heapsort(int a[],int n) {
int i,t;
heapify(a,n);
for (i=n-1;i>0;i--) {
t = a[0];
a[0] = a[i];
a[i] = t;
adjust(a,i);
}
}
void heapify(int a[],int n) {
int k,i,j,item;
for (k=1;k<n;k++) {
item = a[k];
i = k;
j = (i-1)/2;
while((i>0)&&(item>a[j])) {
a[i] = a[j];
i = j;
j = (i-1)/2;
}
a[i] = item;
}
}
void adjust(int a[],int n) {
int i,j,item;
j = 0;
item = a[j];
i = 2*j+1;
while(i<=n-1) {
if(i+1 <= n-1)
if(a[i] <a[i+1])
i++;
if(item<a[i]) {
a[j] = a[i];
j = i;
i = 2*j+1;
} else
break;
}
a[j] = item;
}

Output:
Enter the limit:
5
Enter the list

Bit Institute Of Technology, Hindupur. Page 21


DATA STRUCTURES

20 10 50 40 30
Sorted list is
10 20 30 40 50.

External sort:
External sorting is a class of sorting algorithms that can handle massive amounts of data.
External sorting is required when the data being sorted do not fit into the main memory of a computing device (usually RAM)
and instead they must reside in the slower external memory, usually a hard disk drive.
External sorting typically uses a hybrid sort-merge strategy. In the sorting phase, chunks of data small enough to fit in main
memory are read, sorted, and written out to a temporary file. In the merge phase, the sorted subfiles are combined into a single
larger file.
External merge sort is based on the internal sorting and external merging principle.
1. Divide the data set into run lists that fit into main memory(RAM)
2. Sort this run lists with internal sorting
3. Merge this runs and build the completely sorted data set.

Run 1
Run 1 and 2
Run 2
Run 1 and 2, 3, 4
Run 3
Run 3 and 4
Run 4

Example:

Bit Institute Of Technology, Hindupur. Page 22


DATA STRUCTURES

Time Complexities of various comparison based Algorithms are described in table:

Best case Average case Worst case

Bubble sort O(n^2) O(n^2) O(n^2)

Selection sort O(n^2) O(n^2) O(n^2)

Insertion sort O(n) O(n^2) O(n^2)

Heap sort O(n log n) O(n log n) O(n log n)

Quick sort O(n log n) O(n log n) O(n^2)

Merge sort O(n log n) O(n log n) O(n log n)

Bit Institute Of Technology, Hindupur. Page 23

S-ar putea să vă placă și