Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 56

Sorting

• Sorting refers to arranging data in a particular


format.
• The importance of sorting lies in the fact that
data searching can be optimized to a very high
level, if data is stored in a sorted manner.
• some of the examples of sorting
• Telephone Directory
• Dictionary
• Sorting is of two types
• Internal Sorting
• External Sorting
Complexity of Sorting Algorithms

• The complexity of sorting algorithm calculates the


running time of a function in which ‘n’ numbers
of items are to be sorted.
• Noteworthy of these considerations are:
• The length of time spent by the programmer in
programming a specific sorting program
• Amount of machine time necessary for running
the program
• The amount of memory necessary for running the
program
Efficiency of Sorting Techniques

• To get the amount of time required to sort an


array of ‘n’ elements by a particular method,
the normal approach is to analyze the method
to find the number of comparisons (or
exchanges) required by it
Types of Sorting Techniques

• Bubble Sort.
• Selection Sort.
• Merge Sort.
• Insertion Sort.
• Quick Sort.
• Heap Sort
Time Complexities of all Sorting
Algorithms
Algorithm Time Complexity

Best Average Worst

Selection Sort O(n^2) O(n^2) O(n^2)

Bubble Sort O(n) 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))


QuickSort
• Let's say we are sorting elements in array A,
i.e, quicksort(A);
1. If the number of elements in A is 0 or 1, just
return the array as your answer
2. Otherwise, Pick one element from the array.
This element will be called "pivot"
3. Excluding the pivot, divide A into two
partition
• The first partition contains elements that are
less than or equal to the pivot
• The second partition contains elements that
are greater than or equal to the pivot
4. The overall answer is
quicksort(Part1) ++ pivot ++ quicksort(Part2)
Choosing Pivot
• First element
• Last element
• Middle element
• Do not choose the first element of A because
if the array is originally nearly sorted or
reversed sorted, All the elements will go to
only one partition.
• You should choose the pivot randomly.

• Another way is to choose the median value


from the first, the last, and the middle
element of the array.
Example

and 6 is chosen as the pivot.


• 1. Swap pivot with the last element, we get
Let i and j be index shown in the picture.
2. While i is still on the left of j
• Move i to the right, do not stop until encounter the
element that is greater than or equal to the pivot
• Move j to the left, do not stop until encounter the
element that is less than or equal to the pivot
• When i and j has stopped, we swap the element at i and
j.
This is an attempt to move the small number to the front
and large number to the back.
In this example, 8 and 2 must swap position.
• repeat
• 3. When i is not on the left of j, swap i with
the pivot. Now the smaller numbers are on
the left of the pivot and the larger numbers
are on the right of the pivot.
• Write C programs that implement Quick sort,
to sort a given list of integers in ascending
order
#include<stdio.h>
void qsort(int[],int,int);
void main()
{
int n,i,a[10];
printf("enter n value ");
scanf("%d",&n);
printf("enter the elements ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
qsort(a,0,n-1);
printf(" output sorted list is \n");
for(i=0;i<n;i++)
printf("%3d",a[i]);
}
void qsort(int a[10],int left,int right)
{
int p,i,j,t;
if(left<right)
{
p=a[left];
i=left;
j=right;
do
{
do
{
i++;
}while(a[i]<=p&&i<=right);
while(a[j]>p&&j>left)
{
j--;
}
if(i<j)
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}while(i<j);
t=a[j];
a[j]=a[left];
a[left]=t;
qsort(a,left,j-1);
qsort(a,j+1,right);
}
else
return;

}
• The time complexity of quicksort is dependent
upon the partition and how sorted the list
already is.
• There are some cases where we’re likely to fall
into the trap of choosing a pivot that’s not
near the median of a dataset. In fact, we kind
of fell right into this trap just now!
• For arrays that are nearly or completely
sorted, quicksort operates at its worst. In
other words, the average runtime for a sorted
or a nearly-sorted list is quicksort’s worst case
runtime: O(n²).
• This is particularly important to remember if
we know that we’ll be dealing with data that’s
mostly sorted. In those situations, we want to
stay away from quicksort, since it’s going to
take a really long time to run.
Merge Sort

• 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. The merge(arr, l, m, r) is key process
that assumes that arr[l..m] and arr[m+1..r] are
sorted and merges the two sorted sub-arrays
into one.
MergeSort(arr[], l, r)
If r > l
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)
• An example array {38, 27, 43, 3, 9, 82, 10}.
• The array is recursively divided in two halves
till the size becomes 1. Once the size becomes
1, the merge processes comes into action and
starts merging arrays back till the complete
array is merged.
• Write C programs that implement Merge Sort,
to sort a given list of integers in ascending
order
#include<stdio.h>
#include<conio.h>
int a[10],n;
void getdata();
void display();
void msort(int,int);
void merge(int,int);
void main()
{
clrscr();
getdata();
display();
msort(0,n-1);
display();
}
void getdata()
{
int i;
printf("enter the n value");
scanf("%d",&n);
printf("enter the array elements");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
}
void display()
{
int i;
printf("\n the array elements \n");
for(i=0;i<n;i++)
printf("%3d",a[i]);
}
void msort(int left,int right)
{
int mid;
if(left<right)
{
mid=(left+right)/2;
msort(left,mid);
msort(mid+1,right);
merge(left,right);
}
else
return;

}
void merge(int first,int last)
{
int b[10],mid,i1,i2,i3,k,k1;
mid=(first+last)/2;
i1=first;
i2=mid+1;
i3=0;
while(i1<=mid&&i2<=last)
{
if(a[i1]<a[i2])
b[i3++]=a[i1++];
else
b[i3++]=a[i2++];

}
for(;i1<=mid;)
b[i3++]=a[i1++];
for(;i2<=last;)
b[i3++]=a[i2++];
for(k=first,k1=0;k<=last;k++,k1++)
a[k]=b[k1];
}
• The time complexity of merge sort is O(n log
n). Recursive nature of merge sort results for
O(n log n). Each Recursive call has O(n) steps
and there are log n steps to get the final
solution. so, it results for O(n log n).
Practice Problem
• Given an array A[] and a number x, check for
pair in A[] with sum as x
• Write a C program that, given an array A[] of n
numbers and another number x, determines
whether or not there exist two elements in S
whose sum is exactly x.
Algorithm:

hasArrayTwoCandidates (A[], ar_size, sum)


1) Sort the array in non-decreasing order.
2) Initialize two index variables to find the candidate
elements in the sorted array.
(a) Initialize first to the leftmost index: l = 0
(b) Initialize second the rightmost index: r = ar_size-1
3) Loop while l < r.
(a) If (A[l] + A[r] == sum) then return 1
(b) Else if( A[l] + A[r] < sum ) then l++
(c) Else r--
4) No candidates in whole array - return 0
include <stdio.h>
# define bool int

void quickSort(int *, int, int);

bool hasArrayTwoCandidates(int A[], int arr_size, int sum)


{
int l, r;

/* Sort the elements */


quickSort(A, 0, arr_size-1);

/* Now look for the two candidates in the sorted


array*/
l = 0;
r = arr_size-1;
while (l < r)
{
if(A[l] + A[r] == sum)
return 1;
else if(A[l] + A[r] < sum)
l++;
else // A[i] + A[j] > sum
r--;
}
return 0;
}
int main()
{
int A[] = {1, 4, 45, 6, 10, -8};
int n = 16;
int arr_size = 6;

if( hasArrayTwoCandidates(A, arr_size, n))


printf("Array has two elements with sum 16");
else
printf("Array doesn't have two elements with sum 16 ");

getchar();
return 0;
}
/* FOLLOWING FUNCTIONS ARE ONLY FOR SORTING
PURPOSE */
void exchange(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}

int partition(int A[], int si, int ei)


{
int x = A[ei];
int i = (si - 1);
int j;

for (j = si; j <= ei - 1; j++)


{
if(A[j] <= x)
{
i++;
exchange(&A[i], &A[j]);
}
}
exchange (&A[i + 1], &A[ei]);
return (i + 1);
}
/* Implementation of Quick Sort
A[] --> Array to be sorted
si --> Starting index
ei --> Ending index
*/
void quickSort(int A[], int si, int ei)
{
int pi; /* Partitioning index */
if(si < ei)
{
pi = partition(A, si, ei);
quickSort(A, si, pi - 1);
quickSort(A, pi + 1, ei);
}
}
Merge an array of size n into another
array of size m+n
• There are two sorted arrays. First one is of size
m+n containing only m elements. Another one
is of size n and contains n elements. Merge
these two arrays into the first array of size
m+n such that the output is sorted.
Count Inversions in an array | Set 1
(Using Merge Sort)
• Inversion Count for an array indicates – how far
(or close) the array is from being sorted. If array is
already sorted then inversion count is 0. If array is
sorted in reverse order that inversion count is the
maximum.
Formally speaking, two elements a[i] and a[j]
form an inversion if a[i] > a[j] and i < j
• Example:
The sequence 2, 4, 1, 3, 5 has three inversions (2,
1), (4, 1), (4, 3).
Two elements whose sum is closest to
zero

• An Array of integers is given, both +ve and -ve.


You need to find the two elements such that
their sum is closest to zero.
Find a triplet that sum to a given
value

• Given an array and a value, find if there is a


triplet in array whose sum is equal to the
given value. If there is such a triplet present in
array, then print the triplet and return
true. Else return false. For example, if the
given array is {12, 3, 4, 1, 6, 9} and given sum
is 24, then there is a triplet (12, 3 and 9)
present in array whose sum is 24.
Method-1
• A simple method is to generate all possible
triplets and compare the sum of every triplet
with the given value. The following code
implements this simple method using three
nested loops
1) Sort the input array.
2) Fix the first element as A[i] where i is from 0
to array size – 2. After fixing the first element of
triplet, find the other two elements using
method 1 of this post.
Find a pair with the given difference

• Given an unsorted array and a number n, find if


there exists a pair of elements in the array whose
difference is n.
• Examples
• Input: arr[] = {5, 20, 3, 2, 50, 80}, n=78
• Output: Pair Found: (2, 80)

• Input: arr[] = {90, 70, 20, 80, 50}, n = 45


• Output: No Such Pair
Earth and The Meteorites

• Once upon a time, the Earth was a flat


rectangular landmass. And there was no life. It
was then that the sky lit up with meteorites
falling from out of space. Wherever they fell
on the planet, a river was born, which flowed
in all 4 directions (North, East, West, South),
till the waters reached the edge of the Earth
and simply fell off into space.
• Now, these rivers criss-crossed and divided the
one huge landmass (Pangaea) into many
smaller landmasses. Now the lifeless (there
was no life, remember?), want to know the
number of landmasses on the planet after all
the meteorites have fallen. They also want to
know the area of the smallest and largest
landmass. Can you help the lifeless in this
question?
• Input:
• First line contains T which is the number of test
cases.
• First line of every test case contains 3 integers N,
M, Q where N and M are coordinates of the
bottom right corner of the planet and Q is the
number of meteorites.
The next Q lines contains the
coordinates X, Y where each of the meteorites
fell.
• Output:
• For each test case, output a line containing 3
integers indicating the number of regions, the
minimum area and the maximum area.
Constraints

• 1 ≤ T ≤ 10
• 2 ≤ N, M ≤ 105
• 0 ≤ Q ≤ 105
• 1≤X≤N
• 1≤Y≤M
• 0 ≤ sum of Q over all test cases
Note:

• The Earth can be assumed to be a rectangle


with top left point as (1,1) and bottom right
point (N,M).
• More than one meteorite may have landed at
some point.
• The rivers may be assumed to be flowing in
very thin straight lines parallel to the edges of
the planet.
• SAMPLE INPUT

• 1
• 552
• 23
• 44

• SAMPLE OUTPUT

• 914

You might also like