0% found this document useful (0 votes)
13 views

Ds Unit 5

Uploaded by

Gokulakrishnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Ds Unit 5

Uploaded by

Gokulakrishnan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

UNIT-5

SORTING
INTRODUCTION
Sorting is a technique of organizing the data. It is a process of arranging the records,
either in ascending or descending order i.e. bringing some order lines in the data. Sort methods
are very important in Data structures.
Sorting can be performed on any one or combination of one or more attributes present in
each record. It is very easy and efficient to perform searching, if data is stored in sorting order.
The sorting is performed according to the key value of each record. Depending up on the
makeup of key, records can be stored either numerically or alphanumerically. In numerical
sorting, the records arranged in ascending or descending order according to the numeric value
of the key.
Let A be a list of n elements A1, A2, A3 …………………….An in memory. Sorting A
refers to the operation of rearranging the contents of A so that they are increasing in order, that
is, so that A1 <=A2 <=A3 <=…………….<=An. Since A has n elements, there are n! Ways
that the contents can appear in A. these ways corresponding precisely to the n! Permutations of
1,2,3,………n. accordingly each sorting algorithm must take care of these n! Possibilities.
Ex: suppose an array DATA contains 8elements as follows: DATA: 70,
30,40,10,80,20,60,50. After sorting DATA must appear in memory as follows: DATA: 10 20
30 40 50 60 70 80 Since DATA consists of 8 elements, there are 8!=40320 ways that the
numbers10,20,30,40,50,60,70,80 can appear in DATA.
The factors to be considered while choosing sorting techniques are:
 Programming Time
 Execution Time
 Number of Comparisons
 Memory Utilization
 Computational Complexity
Types of Sorting Techniques:
Internal Sorting: Internal sorting method is used when small amount of data has to be
sorted. In this method , the data to be sorted is stored in the main memory (RAM).Internal
sorting method can access records randomly. EX: Bubble Sort, Insertion Sort, Selection Sort,
Shell sort, Quick Sort, Radix Sort, Heap Sort etc.
External Sorting: Extern al sorting method is used when large amount of data has to be
sorted. In this method, the data to be sorted is stored in the main memory as well as in the
secondary memory such as disk. External sorting methods an access records only in a
sequential order.
Insertion sort
Insertion sort is a simple sorting algorithm that works similar to the way you sort
playing cards in your hands. The array is virtually split into a sorted and an unsorted part.
Values from the unsorted part are picked and placed at the correct position in the sorted part.

Algorithm

To sort an array of size n in ascending order:


1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before. Move
the greater elements one position up to make space for the swapped element.
Time Complexity of InsertionSort

Best Case : O(n) #Means array is already sorted.


Average Case : O(n²) #Means array with random numbers.
Worst Case : O(n²) #Means array with descending order.

Example:
Let us sort the following numbers using Insertion sort mechanism,

12, 11, 13, 5, 15


Let us loop for i = 1 (second element of the array) to 4 (last element of the array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12

11, 12, 13, 5, 15


i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13

11, 12, 13, 5, 15


i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one position
ahead of their current position.

5, 11, 12, 13, 15


i = 4. 15 will be at position 5 as all the elements are smaller than 15.

5, 11, 12, 13,15

Implementation
def insertion_sort(array):for i in range(len(array)):
for j in range(0,i+1):
if array[i] < array[j]:
array[i],array[j] = array[j] ,array[i] for val in array:
print(val,end = " ")print("Enter elements into the array")
array = [int(n) for n in input().split()]
insertion_sort(array)
Output:
Enter elements into the array
15324
Elements After Sorting
1 2 3 4 52.
Enter elements into the array
12 11 13 5 15
Elements After Sorting
5 11 12 13 15
Quick sort

This is the best sort Technique. Quick Sort is a Divide and Conquer algorithm. It picks an
element as pivot and partitions the given array around the picked pivot. There are many
different versions of quick Sort that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot
3. Pick a random element as pivot.
4. Pick median as pivot.

Time Complexity :
Best Case : O(nlogn) #Means array is already sorted.
Average Case : O(nlogn) #Means array with random numbers.
Worst Case : O(n^2) #Means array with descending order.
Algorithm:
1. First element is considered as pivot in the implemented code below.
2. Then we should move all the elements which are less than pivot to one side and greater
than pivot to other side.
3. We divide the array into two arrays in such a way that elements > pivot and elements <
pivot.

Implementation:

#include<stdio.h>
#include<conio.h>
void quicksort(int a[25],int first,int last)
{
int i,j,pivot,temp;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}}
void main()
{
int i,n,a[25];
clrscr();
printf("\nEnter The Number of Elemens:");
scanf("%d",&n);
printf("\nEnter The values:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("\nSorted Elements:\n");
for(i=0;i<n;i++)
printf("\n%d",a[i]);
getch();
}
Merge Sort Algorithm:
One of the best sorting technique. If n value is large, it follows divide and conquer
approach. Like QuickSort, Merge Sort is a Divide and Conquer algorithm. It divides input array
in two halves, calls itself for the two halves and then merges the two sorted halves. The
merge() function is used for merging two halves.
Time Complexity :
Best Case : O(nlogn) #Means array is already sorted.
Average Case : O(nlogn) #Means array with random numbers.
Worst Case : O(nlogn) #Means array with descending order.
Algorithm:
1. Find the middle point to divide the array into two halves:
middle m = (l+r)/2
2. Call mergeSort for first half:
Call mergeSort(arr, l, m)
3. Call mergeSort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
Example:
Let us take an array of elements 16,75,19,12,33,2,310,45,54
Partition Mechanism :
Heap sort
Heap sort is a comparison-based sorting algorithm that sorts an array in ascending or
descending order by transforming it into a binary heap data structure. It uses the concepts of
max-heap and min-heap, where in max-heap, the largest element is the root node, and in min-
heap, the smallest element is the root node. The algorithm uses the binary heap structure to
efficiently sort the elements.

What is Heapify?
Heapify is the process of converting a binary tree into a valid heap data structure. This is
usually achieved by starting from the last internal node (i.e., the parent of the rightmost leaf
node) and working towards the root node, swapping the node with its largest (or smallest,
depending on whether it is a max or min heap) child node until the heap property is satisfied.
The process is repeated for the affected subtrees until the entire tree is a valid heap. The time
complexity of heapify is O(log n), where n is the number of nodes in the tree.

Heap Sort Algorithm

Here are the steps of the Heap Sort algorithm:

 Build a max-heap from the input data: The first step is to build a binary max-heap from
the input data. This is done by transforming the array into a complete binary tree where
the largest value is at the root node.
 Swap the first and last elements of the array: After building the max heap, the largest
value will be at the root node. Swap this value with the last element of the array. This will
place the largest value at the end of the array, which is its final position in the sorted
array.
 Heapify the remaining data: After swapping the first and last elements, the heap size is
reduced by one. The root node may now violate the max-heap property, so the algorithm
needs to reheapify the data to restore the max-heap.
 Repeat steps 2 and 3 until the heap size is reduced to 1: The algorithm continues to
repeat steps 2 and 3 until the heap size is reduced to 1. This means that the entire array
has been sorted in ascending order.
 Return the sorted array: After the heap size has been reduced to 1, the array is sorted
and can be returned as the final result.
Example:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy