SlideShare a Scribd company logo
Sorting
Sorting
Sorting is a process of ordering or placing a list of elements from a collection in some kind of
order. It is nothing but storage of data in sorted order. Sorting can be done in ascending and
descending order. It arranges the data in a sequence which makes searching easier.
For example: The below list of characters is sorted in increasing order of their ASCII values. That
is, the character with lesser ASCII value will be placed first than the character with higher ASCII
value.
d a t a s t r u c t u r e a a c d e r r s t t t u u
Input Output
Categories of Sorting
The techniques of sorting can be divided into two categories. These are:
 Internal Sorting
 External Sorting
Internal Sorting: If all the data that is to be sorted can be adjusted at a time in the main memory,
the internal sorting method is being performed. Example: bubble sort, insertion sort.
External Sorting: When the data that is to be sorted cannot be accommodated in the memory at
the same time and some has to be kept in auxiliary memory such as hard disk, floppy disk, magnetic
tapes etc, then external sorting methods are performed. Example: merge sort.
Stable and Not Stable Sorting
If a sorting algorithm, after sorting the contents, does not change the sequence of similar content
in which they appear, it is called stable sorting.
If a sorting algorithm, after sorting the contents, changes the sequence of similar content in which
they appear, it is called unstable sorting.
Adaptive and Non-Adaptive Sorting Algorithm
A sorting algorithm is said to be adaptive, if it takes advantage of already 'sorted' elements in the
list that is to be sorted. That is, while sorting if the source list has some element already sorted,
adaptive algorithms will take this into account and will try not to re-order them.
A non-adaptive algorithm is one which does not take into account the elements which are already
sorted. They try to force every single element to be re-ordered to confirm their sortedness.
Important Terms
Some terms are generally coined while discussing sorting techniques, here is a brief introduction
to them −
Increasing Order
A sequence of values is said to be in increasing order, if the successive element is greater than
the previous one. For example, 1, 3, 4, 6, 8, 9 are in increasing order, as every next element is
greater than the previous element.
Decreasing Order
A sequence of values is said to be in decreasing order, if the successive element is less than the
current one. For example, 9, 8, 6, 4, 3, 1 are in decreasing order, as every next element is less than
the previous element.
Non-Increasing Order
A sequence of values is said to be in non-increasing order, if the successive element is less than
or equal to its previous element in the sequence. This order occurs when the sequence contains
duplicate values. For example, 9, 8, 6, 3, 3, 1 are in non-increasing order, as every next element
is less than or equal to (in case of 3) but not greater than any previous element.
Non-Decreasing Order
A sequence of values is said to be in non-decreasing order, if the successive element is greater
than or equal to its previous element in the sequence. This order occurs when the sequence
contains duplicate values. For example, 1, 3, 3, 6, 8, 9 are in non-decreasing order, as every next
element is greater than or equal to (in case of 3) but not less than the previous one.
The Bubble Sort
The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges
those that are out of order. Each pass through the list places the next largest value in its proper
place. In essence, each item “bubbles” up to the location where it belongs.
Example. Sort {5, 1, 12, -5, 16} using bubble sort.
Table 1: Comparisons for Each Pass of Bubble Sort
Pass Comparisons
1 n−1
2 n−2
3 n−3
… …
n−1 1
Algorithm for bubble sort
1. Input array A[1….n]
2. for (i = 0; i<= n – 1; i++)
{
for (j= 0; j<=n - i – 1; j++)
{
if (A[j] > A[j+1]) {
temp = A[j];
A[j] = A[j+1];
A[j+1] = temp;
}
}
}
3. Output: Sorted list
Sample Code
#include <stdio.h>
int main()
{
int array[100], n, c, d, swap;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d integersn", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
for (c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
printf("Sorted list in ascending order:n");
for ( c = 0 ; c < n ; c++ )
printf("%dn", array[c]);
return 0;
}
Sample Output
Enter number of elements
6
Enter 6 integers
8
9
0
-2
1
4
Sorted list in ascending order:
-2
0
1
4
8
9
The Selection Sort
In this method, at first we select the smallest data of the list. After selecting, we place the smallest
data in the first position and the data in first position is placed in the position where the smallest
data was. After that we consider the list except the data in the first position. Again we select the
(second) smallest data from the list and place it in the second position of the list and place the data
in the in the second position, in the position where the second smallest data was. By repeating the
process, we can sort the whole list.
Example. Sort {5, 1, 12, -5, 16, 2, 12, 14} using selection sort.
Algorithm for selection sort
1. Input array A[1…..n]
2. for(i=1; i<=n-1; i++)
{
small_index=i;
for(j=i+1; j<=n; j++)
{
if(A[j] < A[small_index])
small_index=j;
}
temp=A[i];
A[i]=A[small_index];
A[small_index]=temp;
}
3. Output: Sorted list
Sample Code
#include<stdio.h>
#include<conio.h>
int main()
{
int i,j,n,a[100],small_index,temp;
printf("Enter the number of elementn");
scanf("%d",&n);
printf("Enter the elementn");
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<=(n-1);i++)
{
small_index=i;
for(j=i+1;j<=n;j++)
{
if(a[j]<a[small_index])
small_index=j;
}
temp=a[i];
a[i]=a[small_index];
a[small_index]=temp;
}
printf("Sorted numbern");
for(i=1;i<=n;i++)
{
printf("%d",a[i]);
printf("n");
}
getch();
return 0;
}
Sample Output
Enter the number of element
4
Enter the element
-1
-2
5
6
Sorted number
-2
-1
5
6
The Insertion Sort
It always maintains a sorted sublist in the lower positions of the list. Each new item is then
“inserted” back into the previous sublist such that the sorted sublist is one item larger. Figure
shows the insertion sorting process. The shaded items represent the ordered sublists as the
algorithm makes each pass. We can derive simple steps by which we can achieve insertion sort.
Algorithm for insertion sort
1. Input array A[1….n]
2. for (i = 1 ; i <= n - 1; i++) {
j = i;
while ( j > 0 && a[j-1] > a[j]) {
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
j--;
}
}
3. Output: Sorted list.
Sample Code
#include<stdio.h>
#include<conio.h>
int main()
{
int n, a[1000], i, j, temp;
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d integersn", n);
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (i = 1 ; i <= n - 1; i++) {
j = i;
while ( j > 0 && a[j-1] > a[j]) {
temp = a[j];
a[j] = a[j-1];
a[j-1] = temp;
j--;
}
}
printf("Sorted list in ascending order:n");
for (i = 0; i <= n - 1; i++) {
printf("%dn", a[i]);
}
return 0;
}
Sample Output
Enter number of elements
8
Enter 8 integers
-1
5
8
2
3
0
6
5
Sorted list in ascending order:
-1
0
2
3
5
5
6
8
Divide and Conquer Method
In divide and conquer approach, the problem in hand, is divided into smaller sub-problems and
then each problem is solved independently. When we keep on dividing the subproblems into even
smaller sub-problems, we may eventually reach a stage where no more division is possible. Those
"atomic" smallest possible sub-problem (fractions) are solved. The solution of all sub-problems
is finally merged in order to obtain the solution of an original problem.
Broadly, we can understand divide-and-conquer approach in a three-step process.
Divide/Break
This step involves breaking the problem into smaller sub-problems. Sub-problems should
represent a part of the original problem. This step generally takes a recursive approach to divide
the problem until no sub-problem is further divisible. At this stage, sub-problems become atomic
in nature but still represent some part of the actual problem.
Conquer/Solve
This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the problems
are considered 'solved' on their own.
Merge/Combine
When the smaller sub-problems are solved, this stage recursively combines them until they
formulate a solution of the original problem. This algorithmic approach works recursively and
conquer & merge steps works so close that they appear as one.
The Merge Sort
Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has
one item, it is sorted by definition (the base case). If the list has more than one item, we split the
list and recursively invoke a merge sort on both halves. Once the two halves are sorted, the
fundamental operation, called a merge, is performed. Merging is the process of taking two smaller
sorted lists and combining them together into a single, sorted, new list.
Figure 1: Splitting the List in a Merge Sort
Figure 2: Lists as They Are Merged Together
Algorithm for Merge Sort
Algorithm MergeSort(l,h)
{
if(l<h)
{
Mid=(l+h)/2;
MergeSort(l,mid);
MergeSort(Mid+1,h);
Merge(l,mid,h);
}
}
Algorithm Merge(A,B,m,n)
{
i=1,j=1,k=1;
while(i<=m && j<=n)
A B C
2=i 5=j 2=k
8 9 5
15 12 8
18 17 9
12
15
17
18
Size=m Size=n Size=m+n
1 2 3 4 5 6 7 8
9 3 7 5 6 4 8 2
1,8
1,4 5,8
1,2 3,4 5,6 7,8
1,1 2,2 3,3 4,4 5,5 6,6 7,7 8,8
{
if(A[i]<B[j])
C[k++]=A[i++];
else
C[k++]=B[j++];
}
for(;i<=m;i++)
C[k++]=A[i];
for(;j<=n;j++)
C[k++]=B[j];
}
Sample Code
#include<stdio.h>
#include<conio.h>
int a[20],b[30];
void Merge(int low,int mid,int high);
void MergeSort(int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
MergeSort(low,mid);
MergeSort(mid+1,high);
Merge(low,mid,high);
}
}
void Merge(int low,int mid,int high)
{
int h,i,j;
h=low,i=low,j=mid+1;
while((h<=mid)&&(j<=high))
{
if(a[h]<=a[j])
{
b[i]=a[h];
h++;
}
else
{
b[i]=a[j];
j++;
}
i++;
}
if(h>mid)
{
for(int k=j;k<=high;k++)
{
b[i]=a[k];
i++;
}
}
else
{
for(int k=h;k<=mid;k++)
{
b[i]=a[k];
i++;
}
}
for( int k=low;k<=high;k++)
a[k]=b[k];
}
int main()
{
int i, n,c=1;
printf("Enter range of arrayn");
scanf("%d",&n);
printf("Enter the array element: ");
for(i=1;i<=n;i++)
scanf("%d",&a[i]);
MergeSort(c,n);
printf("Sorted array element: ");
for(i=1;i<=n;i++)
printf("%d ",a[i]);
getch();
return 0;
}
Sample Output
Enter range of array
5
Enter the array element:
1
7
-2
6
8
Sorted array element: -2 1 6 7 8
Quick Sort
Quicksort is a sorting algorithm based on the divide and conquer approach where
 An array is divided into subarrays by selecting a pivot element (element selected from the
array). While dividing the array, the pivot element should be positioned in such a way that
elements less than pivot are kept on the left side and elements greater than pivot are on the
right side of the pivot.
 The left and right subarrays are also divided using the same approach. This process
continues until each subarray contains a single element.
 At this point, elements are already sorted. Finally, elements are combined to form a sorted
array.
Example:
0 1 2 3 4 5 6 7
50=i 30 10 90 80 20 40 70=j
Pivot=50
0 1 2 3 4 5 6 7
50 30 10 90=i 80 20 40=j 70
0 1 2 3 4 5 6 7
50 30 10 40=i 80 20 90=j 70
0 1 2 3 4 5 6 7
50 30 10 40 80=i 20=j 90 70
0 1 2 3 4 5 6 7
50 30 10 40 20=i 80=j 90 70
0 1 2 3 4 5 6 7
50 30 10 40 20=j 80=i 90 70
0 1 2 3 4 5 6 7
20 30 10 40 50 80 90 70
Left Half
0 1 2 3
20=i 30 10 40=j
Pivot=20
0 1 2 3
20 30=i 10=j 40
0 1 2 3
20 10=i 30=j 40
0 1 2 3
20 10=j 30=i 40
0 1 2 3
10 20 30 40
Right Half
5 6 7
80=i 90 70=j
Pivot=80
5 6 7
80 90=i 70=j
5 6 7
80 70=i 90=j
5 6 7
80 70=j 90=i
5 6 7
70 80 90
Finally
0 1 2 3 4 5 6 7
10 20 30 40 50 70 80 90
Algorithm for Quick Sort
Algorithm QuickSort(l,h)
{
if(l<h)
{
j=Partition(l,h);
QuickSort(l,j);
QuickSort(j+1,h);
}
}
Algorithm Partition(l,h)
{
Pivot=A[l];
i=l,j=h;
while(i<j)
{
do
{
i++;
}while(A[i]<=pivot);
do
{
j--;
}while(A[j]>pivot);
if(i<j)
swap(A[i],A[j]);
}
Swap(A[l],A[j]);
return j;
}
Sample Code
#include<stdio.h>
#include<conio.h>
int Partition(int a[],int m,int p);
void Interchange(int a[],int i,int j);
int a[100];
void QuickSort(int p,int q)
{ int j;
if(p<q)
{
j=Partition(a,p,q+1);
QuickSort(p,j-1);
QuickSort(j+1,q);
}
}
int Partition(int a[],int m,int p)
{
int pivot,j,i;
pivot=a[m],i=m,j=p;
do
{
do
{
i++;
}while(a[i]<=pivot);
do
{
j--;
}while(a[j]>pivot);
if(i<j)
Interchange(a,i,j);
}while(i<=j);
a[m]=a[j];
a[j]=pivot;
return j;
}
void Interchange(int a[],int i,int j)
{
int p;
p=a[i];
a[i]=a[j];
a[j]=p;
}
int main()
{
int k,n,c=1,temp;
printf("Enter the range of arrayn");
scanf("%d",&n);
printf("Enter an infinite numbern");
scanf("%d",&temp);
printf("Input the arrayn");
for(k=1;k<=n;k++)
scanf("%d",&a[k]);
a[n+1]=temp;
QuickSort(c,n);
printf("Output arrayn");
for(k=1;k<=n;k++)
printf("%dt",a[k]);
return 0;
}
Sample Output
Enter the range of array
7
Enter an infinite number
100000
Input the array
6
7
5
6
0
0
3
Output array
0 0 3 5 6 6 7

More Related Content

What's hot

Searching in c language
Searching in c languageSearching in c language
Searching in c language
CHANDAN KUMAR
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & AlgorithumsAin-ul-Moiz Khawaja
 
Data structure
Data  structureData  structure
Data structure
Arvind Kumar
 
Searching Sorting
Searching SortingSearching Sorting
Searching Sortingguest2cb109
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
maamir farooq
 
Data Structure and Algorithms Arrays
Data Structure and Algorithms ArraysData Structure and Algorithms Arrays
Data Structure and Algorithms Arrays
ManishPrajapati78
 
Loop Like a Functional Programing Native
Loop Like a Functional Programing NativeLoop Like a Functional Programing Native
Loop Like a Functional Programing Native
Jiaming Zhang
 
Data structure using c module 3
Data structure using c module 3Data structure using c module 3
Data structure using c module 3
smruti sarangi
 
2 data structure in R
2 data structure in R2 data structure in R
2 data structure in R
naroranisha
 
6. R data structures
6. R data structures6. R data structures
6. R data structures
ExternalEvents
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
Rai University
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
Hoang Nguyen
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structureTushar Aneyrao
 
Data Structures (BE)
Data Structures (BE)Data Structures (BE)
Data Structures (BE)
PRABHAHARAN429
 
Unit 7 sorting
Unit   7 sortingUnit   7 sorting
Unit 7 sorting
Dabbal Singh Mahara
 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
B.Kirron Reddi
 

What's hot (19)

Searching in c language
Searching in c languageSearching in c language
Searching in c language
 
Sorting algorithums > Data Structures & Algorithums
Sorting algorithums  > Data Structures & AlgorithumsSorting algorithums  > Data Structures & Algorithums
Sorting algorithums > Data Structures & Algorithums
 
Data structure
Data  structureData  structure
Data structure
 
Searching Sorting
Searching SortingSearching Sorting
Searching Sorting
 
Data structures arrays
Data structures   arraysData structures   arrays
Data structures arrays
 
Data Structure and Algorithms Arrays
Data Structure and Algorithms ArraysData Structure and Algorithms Arrays
Data Structure and Algorithms Arrays
 
Loop Like a Functional Programing Native
Loop Like a Functional Programing NativeLoop Like a Functional Programing Native
Loop Like a Functional Programing Native
 
Data structure using c module 3
Data structure using c module 3Data structure using c module 3
Data structure using c module 3
 
2 data structure in R
2 data structure in R2 data structure in R
2 data structure in R
 
Lecture 2a arrays
Lecture 2a arraysLecture 2a arrays
Lecture 2a arrays
 
6. R data structures
6. R data structures6. R data structures
6. R data structures
 
R교육1
R교육1R교육1
R교육1
 
Ds notes
Ds notesDs notes
Ds notes
 
Bsc cs ii dfs u-2 linklist,stack,queue
Bsc cs ii  dfs u-2 linklist,stack,queueBsc cs ii  dfs u-2 linklist,stack,queue
Bsc cs ii dfs u-2 linklist,stack,queue
 
Data structures and algorithms
Data structures and algorithmsData structures and algorithms
Data structures and algorithms
 
Array implementation and linked list as datat structure
Array implementation and linked list as datat structureArray implementation and linked list as datat structure
Array implementation and linked list as datat structure
 
Data Structures (BE)
Data Structures (BE)Data Structures (BE)
Data Structures (BE)
 
Unit 7 sorting
Unit   7 sortingUnit   7 sorting
Unit 7 sorting
 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
 

Similar to Sorting

Sorting
SortingSorting
my docoment
my docomentmy docoment
my docoment
NeeshanYonzan
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & Searching
ThenmozhiK5
 
DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptx
prakashvs7
 
366 it elective 4 (analysis of algoritm)
366 it elective 4 (analysis of algoritm)366 it elective 4 (analysis of algoritm)
366 it elective 4 (analysis of algoritm)
Neil Soliven
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
SajalFayyaz
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sorting
nikshaikh786
 
Searching and sorting by B kirron Reddi
Searching and sorting by B kirron ReddiSearching and sorting by B kirron Reddi
Searching and sorting by B kirron Reddi
B.Kirron Reddi
 
Chapter3.pptx
Chapter3.pptxChapter3.pptx
Chapter3.pptx
ASMAALWADEE2
 
Unit vii sorting
Unit   vii sorting Unit   vii sorting
Unit vii sorting
Tribhuvan University
 
Selection sort
Selection sortSelection sort
Selection sortasra khan
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
SeethaDinesh
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
SeethaDinesh
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
poongothai11
 
Sorting
SortingSorting
Sorting
Saharamily
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
haramaya university
 
Searching
SearchingSearching
Searching
A. S. M. Shafi
 

Similar to Sorting (20)

Sorting
SortingSorting
Sorting
 
Unit v data structure-converted
Unit  v data structure-convertedUnit  v data structure-converted
Unit v data structure-converted
 
my docoment
my docomentmy docoment
my docoment
 
Data Structures_ Sorting & Searching
Data Structures_ Sorting & SearchingData Structures_ Sorting & Searching
Data Structures_ Sorting & Searching
 
DS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptxDS - Unit 2 FINAL (2).pptx
DS - Unit 2 FINAL (2).pptx
 
366 it elective 4 (analysis of algoritm)
366 it elective 4 (analysis of algoritm)366 it elective 4 (analysis of algoritm)
366 it elective 4 (analysis of algoritm)
 
Data structure.pptx
Data structure.pptxData structure.pptx
Data structure.pptx
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
 
Heap, quick and merge sort
Heap, quick and merge sortHeap, quick and merge sort
Heap, quick and merge sort
 
MODULE 5-Searching and-sorting
MODULE 5-Searching and-sortingMODULE 5-Searching and-sorting
MODULE 5-Searching and-sorting
 
Searching and sorting by B kirron Reddi
Searching and sorting by B kirron ReddiSearching and sorting by B kirron Reddi
Searching and sorting by B kirron Reddi
 
Chapter3.pptx
Chapter3.pptxChapter3.pptx
Chapter3.pptx
 
Unit vii sorting
Unit   vii sorting Unit   vii sorting
Unit vii sorting
 
Selection sort
Selection sortSelection sort
Selection sort
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
DS UNIT 1.pdf
DS UNIT 1.pdfDS UNIT 1.pdf
DS UNIT 1.pdf
 
Searching and Sorting Algorithms in Data Structures
Searching and Sorting Algorithms  in Data StructuresSearching and Sorting Algorithms  in Data Structures
Searching and Sorting Algorithms in Data Structures
 
Sorting
SortingSorting
Sorting
 
advanced searching and sorting.pdf
advanced searching and sorting.pdfadvanced searching and sorting.pdf
advanced searching and sorting.pdf
 
Searching
SearchingSearching
Searching
 

More from A. S. M. Shafi

2D Transformation in Computer Graphics
2D Transformation in Computer Graphics2D Transformation in Computer Graphics
2D Transformation in Computer Graphics
A. S. M. Shafi
 
3D Transformation in Computer Graphics
3D Transformation in Computer Graphics3D Transformation in Computer Graphics
3D Transformation in Computer Graphics
A. S. M. Shafi
 
Projection
ProjectionProjection
Projection
A. S. M. Shafi
 
2D Transformation
2D Transformation2D Transformation
2D Transformation
A. S. M. Shafi
 
Line drawing algorithm
Line drawing algorithmLine drawing algorithm
Line drawing algorithm
A. S. M. Shafi
 
Fragmentation
FragmentationFragmentation
Fragmentation
A. S. M. Shafi
 
File organization
File organizationFile organization
File organization
A. S. M. Shafi
 
Bankers algorithm
Bankers algorithmBankers algorithm
Bankers algorithm
A. S. M. Shafi
 
RR and priority scheduling
RR and priority schedulingRR and priority scheduling
RR and priority scheduling
A. S. M. Shafi
 
Fcfs and sjf
Fcfs and sjfFcfs and sjf
Fcfs and sjf
A. S. M. Shafi
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
A. S. M. Shafi
 
1D Array
1D Array1D Array
1D Array
A. S. M. Shafi
 
2D array
2D array2D array
2D array
A. S. M. Shafi
 
Stack push pop
Stack push popStack push pop
Stack push pop
A. S. M. Shafi
 
Queue
QueueQueue
Linked list
Linked listLinked list
Linked list
A. S. M. Shafi
 
Sum of subset problem
Sum of subset problemSum of subset problem
Sum of subset problem
A. S. M. Shafi
 
Quick sort
Quick sortQuick sort
Quick sort
A. S. M. Shafi
 
N queens problem
N queens problemN queens problem
N queens problem
A. S. M. Shafi
 
MST
MSTMST

More from A. S. M. Shafi (20)

2D Transformation in Computer Graphics
2D Transformation in Computer Graphics2D Transformation in Computer Graphics
2D Transformation in Computer Graphics
 
3D Transformation in Computer Graphics
3D Transformation in Computer Graphics3D Transformation in Computer Graphics
3D Transformation in Computer Graphics
 
Projection
ProjectionProjection
Projection
 
2D Transformation
2D Transformation2D Transformation
2D Transformation
 
Line drawing algorithm
Line drawing algorithmLine drawing algorithm
Line drawing algorithm
 
Fragmentation
FragmentationFragmentation
Fragmentation
 
File organization
File organizationFile organization
File organization
 
Bankers algorithm
Bankers algorithmBankers algorithm
Bankers algorithm
 
RR and priority scheduling
RR and priority schedulingRR and priority scheduling
RR and priority scheduling
 
Fcfs and sjf
Fcfs and sjfFcfs and sjf
Fcfs and sjf
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
 
1D Array
1D Array1D Array
1D Array
 
2D array
2D array2D array
2D array
 
Stack push pop
Stack push popStack push pop
Stack push pop
 
Queue
QueueQueue
Queue
 
Linked list
Linked listLinked list
Linked list
 
Sum of subset problem
Sum of subset problemSum of subset problem
Sum of subset problem
 
Quick sort
Quick sortQuick sort
Quick sort
 
N queens problem
N queens problemN queens problem
N queens problem
 
MST
MSTMST
MST
 

Recently uploaded

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
EugeneSaldivar
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
Celine George
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
TechSoup
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
vaibhavrinwa19
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
beazzy04
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
Sandy Millin
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
MIRIAMSALINAS13
 

Recently uploaded (20)

678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...TESDA TM1 REVIEWER  FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
TESDA TM1 REVIEWER FOR NATIONAL ASSESSMENT WRITTEN AND ORAL QUESTIONS WITH A...
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17How to Make a Field invisible in Odoo 17
How to Make a Field invisible in Odoo 17
 
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup   New Member Orientation and Q&A (May 2024).pdfWelcome to TechSoup   New Member Orientation and Q&A (May 2024).pdf
Welcome to TechSoup New Member Orientation and Q&A (May 2024).pdf
 
Acetabularia Information For Class 9 .docx
Acetabularia Information For Class 9  .docxAcetabularia Information For Class 9  .docx
Acetabularia Information For Class 9 .docx
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345Sha'Carri Richardson Presentation 202345
Sha'Carri Richardson Presentation 202345
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...2024.06.01 Introducing a competency framework for languag learning materials ...
2024.06.01 Introducing a competency framework for languag learning materials ...
 
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXXPhrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
Phrasal Verbs.XXXXXXXXXXXXXXXXXXXXXXXXXX
 

Sorting

  • 1. Sorting Sorting Sorting is a process of ordering or placing a list of elements from a collection in some kind of order. It is nothing but storage of data in sorted order. Sorting can be done in ascending and descending order. It arranges the data in a sequence which makes searching easier. For example: The below list of characters is sorted in increasing order of their ASCII values. That is, the character with lesser ASCII value will be placed first than the character with higher ASCII value. d a t a s t r u c t u r e a a c d e r r s t t t u u Input Output Categories of Sorting The techniques of sorting can be divided into two categories. These are:  Internal Sorting  External Sorting Internal Sorting: If all the data that is to be sorted can be adjusted at a time in the main memory, the internal sorting method is being performed. Example: bubble sort, insertion sort. External Sorting: When the data that is to be sorted cannot be accommodated in the memory at the same time and some has to be kept in auxiliary memory such as hard disk, floppy disk, magnetic tapes etc, then external sorting methods are performed. Example: merge sort. Stable and Not Stable Sorting If a sorting algorithm, after sorting the contents, does not change the sequence of similar content in which they appear, it is called stable sorting.
  • 2. If a sorting algorithm, after sorting the contents, changes the sequence of similar content in which they appear, it is called unstable sorting. Adaptive and Non-Adaptive Sorting Algorithm A sorting algorithm is said to be adaptive, if it takes advantage of already 'sorted' elements in the list that is to be sorted. That is, while sorting if the source list has some element already sorted, adaptive algorithms will take this into account and will try not to re-order them. A non-adaptive algorithm is one which does not take into account the elements which are already sorted. They try to force every single element to be re-ordered to confirm their sortedness. Important Terms Some terms are generally coined while discussing sorting techniques, here is a brief introduction to them − Increasing Order A sequence of values is said to be in increasing order, if the successive element is greater than the previous one. For example, 1, 3, 4, 6, 8, 9 are in increasing order, as every next element is greater than the previous element. Decreasing Order A sequence of values is said to be in decreasing order, if the successive element is less than the current one. For example, 9, 8, 6, 4, 3, 1 are in decreasing order, as every next element is less than the previous element. Non-Increasing Order A sequence of values is said to be in non-increasing order, if the successive element is less than or equal to its previous element in the sequence. This order occurs when the sequence contains duplicate values. For example, 9, 8, 6, 3, 3, 1 are in non-increasing order, as every next element is less than or equal to (in case of 3) but not greater than any previous element.
  • 3. Non-Decreasing Order A sequence of values is said to be in non-decreasing order, if the successive element is greater than or equal to its previous element in the sequence. This order occurs when the sequence contains duplicate values. For example, 1, 3, 3, 6, 8, 9 are in non-decreasing order, as every next element is greater than or equal to (in case of 3) but not less than the previous one. The Bubble Sort The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that are out of order. Each pass through the list places the next largest value in its proper place. In essence, each item “bubbles” up to the location where it belongs. Example. Sort {5, 1, 12, -5, 16} using bubble sort.
  • 4. Table 1: Comparisons for Each Pass of Bubble Sort Pass Comparisons 1 n−1 2 n−2 3 n−3 … … n−1 1 Algorithm for bubble sort 1. Input array A[1….n] 2. for (i = 0; i<= n – 1; i++) { for (j= 0; j<=n - i – 1; j++) { if (A[j] > A[j+1]) { temp = A[j]; A[j] = A[j+1]; A[j+1] = temp; } } } 3. Output: Sorted list Sample Code #include <stdio.h> int main() { int array[100], n, c, d, swap; printf("Enter number of elementsn"); scanf("%d", &n); printf("Enter %d integersn", n); for (c = 0; c < n; c++) scanf("%d", &array[c]);
  • 5. for (c = 0 ; c < ( n - 1 ); c++) { for (d = 0 ; d < n - c - 1; d++) { if (array[d] > array[d+1]) /* For decreasing order use < */ { swap = array[d]; array[d] = array[d+1]; array[d+1] = swap; } } } printf("Sorted list in ascending order:n"); for ( c = 0 ; c < n ; c++ ) printf("%dn", array[c]); return 0; } Sample Output Enter number of elements 6 Enter 6 integers 8 9 0 -2 1 4 Sorted list in ascending order: -2 0 1 4 8 9 The Selection Sort In this method, at first we select the smallest data of the list. After selecting, we place the smallest data in the first position and the data in first position is placed in the position where the smallest data was. After that we consider the list except the data in the first position. Again we select the (second) smallest data from the list and place it in the second position of the list and place the data
  • 6. in the in the second position, in the position where the second smallest data was. By repeating the process, we can sort the whole list. Example. Sort {5, 1, 12, -5, 16, 2, 12, 14} using selection sort. Algorithm for selection sort 1. Input array A[1…..n] 2. for(i=1; i<=n-1; i++) { small_index=i; for(j=i+1; j<=n; j++) { if(A[j] < A[small_index]) small_index=j; } temp=A[i]; A[i]=A[small_index]; A[small_index]=temp;
  • 7. } 3. Output: Sorted list Sample Code #include<stdio.h> #include<conio.h> int main() { int i,j,n,a[100],small_index,temp; printf("Enter the number of elementn"); scanf("%d",&n); printf("Enter the elementn"); for(i=1;i<=n;i++) { scanf("%d",&a[i]); } for(i=1;i<=(n-1);i++) { small_index=i; for(j=i+1;j<=n;j++) { if(a[j]<a[small_index]) small_index=j; } temp=a[i]; a[i]=a[small_index]; a[small_index]=temp; } printf("Sorted numbern"); for(i=1;i<=n;i++) { printf("%d",a[i]); printf("n"); } getch(); return 0; } Sample Output Enter the number of element 4 Enter the element -1 -2 5
  • 8. 6 Sorted number -2 -1 5 6 The Insertion Sort It always maintains a sorted sublist in the lower positions of the list. Each new item is then “inserted” back into the previous sublist such that the sorted sublist is one item larger. Figure shows the insertion sorting process. The shaded items represent the ordered sublists as the algorithm makes each pass. We can derive simple steps by which we can achieve insertion sort. Algorithm for insertion sort 1. Input array A[1….n] 2. for (i = 1 ; i <= n - 1; i++) { j = i; while ( j > 0 && a[j-1] > a[j]) { temp = a[j];
  • 9. a[j] = a[j-1]; a[j-1] = temp; j--; } } 3. Output: Sorted list. Sample Code #include<stdio.h> #include<conio.h> int main() { int n, a[1000], i, j, temp; printf("Enter number of elementsn"); scanf("%d", &n); printf("Enter %d integersn", n); for (i = 0; i < n; i++) { scanf("%d", &a[i]); } for (i = 1 ; i <= n - 1; i++) { j = i; while ( j > 0 && a[j-1] > a[j]) { temp = a[j]; a[j] = a[j-1]; a[j-1] = temp; j--; } } printf("Sorted list in ascending order:n"); for (i = 0; i <= n - 1; i++) { printf("%dn", a[i]); } return 0; } Sample Output Enter number of elements 8 Enter 8 integers -1 5 8
  • 10. 2 3 0 6 5 Sorted list in ascending order: -1 0 2 3 5 5 6 8 Divide and Conquer Method In divide and conquer approach, the problem in hand, is divided into smaller sub-problems and then each problem is solved independently. When we keep on dividing the subproblems into even smaller sub-problems, we may eventually reach a stage where no more division is possible. Those "atomic" smallest possible sub-problem (fractions) are solved. The solution of all sub-problems is finally merged in order to obtain the solution of an original problem.
  • 11. Broadly, we can understand divide-and-conquer approach in a three-step process. Divide/Break This step involves breaking the problem into smaller sub-problems. Sub-problems should represent a part of the original problem. This step generally takes a recursive approach to divide the problem until no sub-problem is further divisible. At this stage, sub-problems become atomic in nature but still represent some part of the actual problem. Conquer/Solve This step receives a lot of smaller sub-problems to be solved. Generally, at this level, the problems are considered 'solved' on their own. Merge/Combine When the smaller sub-problems are solved, this stage recursively combines them until they formulate a solution of the original problem. This algorithmic approach works recursively and conquer & merge steps works so close that they appear as one. The Merge Sort Merge sort is a recursive algorithm that continually splits a list in half. If the list is empty or has one item, it is sorted by definition (the base case). If the list has more than one item, we split the list and recursively invoke a merge sort on both halves. Once the two halves are sorted, the fundamental operation, called a merge, is performed. Merging is the process of taking two smaller sorted lists and combining them together into a single, sorted, new list. Figure 1: Splitting the List in a Merge Sort
  • 12. Figure 2: Lists as They Are Merged Together Algorithm for Merge Sort Algorithm MergeSort(l,h) { if(l<h) { Mid=(l+h)/2; MergeSort(l,mid); MergeSort(Mid+1,h); Merge(l,mid,h); } } Algorithm Merge(A,B,m,n) { i=1,j=1,k=1; while(i<=m && j<=n) A B C 2=i 5=j 2=k 8 9 5 15 12 8 18 17 9 12 15 17 18 Size=m Size=n Size=m+n 1 2 3 4 5 6 7 8 9 3 7 5 6 4 8 2 1,8 1,4 5,8 1,2 3,4 5,6 7,8 1,1 2,2 3,3 4,4 5,5 6,6 7,7 8,8
  • 13. { if(A[i]<B[j]) C[k++]=A[i++]; else C[k++]=B[j++]; } for(;i<=m;i++) C[k++]=A[i]; for(;j<=n;j++) C[k++]=B[j]; } Sample Code #include<stdio.h> #include<conio.h> int a[20],b[30]; void Merge(int low,int mid,int high); void MergeSort(int low,int high) { int mid; if(low<high) { mid=(low+high)/2; MergeSort(low,mid); MergeSort(mid+1,high); Merge(low,mid,high); } }
  • 14. void Merge(int low,int mid,int high) { int h,i,j; h=low,i=low,j=mid+1; while((h<=mid)&&(j<=high)) { if(a[h]<=a[j]) { b[i]=a[h]; h++; } else { b[i]=a[j]; j++; } i++; } if(h>mid) { for(int k=j;k<=high;k++) { b[i]=a[k]; i++; } } else { for(int k=h;k<=mid;k++) {
  • 15. b[i]=a[k]; i++; } } for( int k=low;k<=high;k++) a[k]=b[k]; } int main() { int i, n,c=1; printf("Enter range of arrayn"); scanf("%d",&n); printf("Enter the array element: "); for(i=1;i<=n;i++) scanf("%d",&a[i]); MergeSort(c,n); printf("Sorted array element: "); for(i=1;i<=n;i++) printf("%d ",a[i]); getch(); return 0; } Sample Output Enter range of array 5 Enter the array element: 1 7 -2 6
  • 16. 8 Sorted array element: -2 1 6 7 8 Quick Sort Quicksort is a sorting algorithm based on the divide and conquer approach where  An array is divided into subarrays by selecting a pivot element (element selected from the array). While dividing the array, the pivot element should be positioned in such a way that elements less than pivot are kept on the left side and elements greater than pivot are on the right side of the pivot.  The left and right subarrays are also divided using the same approach. This process continues until each subarray contains a single element.  At this point, elements are already sorted. Finally, elements are combined to form a sorted array. Example: 0 1 2 3 4 5 6 7 50=i 30 10 90 80 20 40 70=j Pivot=50 0 1 2 3 4 5 6 7 50 30 10 90=i 80 20 40=j 70 0 1 2 3 4 5 6 7 50 30 10 40=i 80 20 90=j 70 0 1 2 3 4 5 6 7 50 30 10 40 80=i 20=j 90 70 0 1 2 3 4 5 6 7 50 30 10 40 20=i 80=j 90 70 0 1 2 3 4 5 6 7 50 30 10 40 20=j 80=i 90 70
  • 17. 0 1 2 3 4 5 6 7 20 30 10 40 50 80 90 70 Left Half 0 1 2 3 20=i 30 10 40=j Pivot=20 0 1 2 3 20 30=i 10=j 40 0 1 2 3 20 10=i 30=j 40 0 1 2 3 20 10=j 30=i 40 0 1 2 3 10 20 30 40 Right Half 5 6 7 80=i 90 70=j Pivot=80 5 6 7 80 90=i 70=j 5 6 7 80 70=i 90=j
  • 18. 5 6 7 80 70=j 90=i 5 6 7 70 80 90 Finally 0 1 2 3 4 5 6 7 10 20 30 40 50 70 80 90 Algorithm for Quick Sort Algorithm QuickSort(l,h) { if(l<h) { j=Partition(l,h); QuickSort(l,j); QuickSort(j+1,h); } } Algorithm Partition(l,h) { Pivot=A[l]; i=l,j=h; while(i<j) { do { i++; }while(A[i]<=pivot); do
  • 19. { j--; }while(A[j]>pivot); if(i<j) swap(A[i],A[j]); } Swap(A[l],A[j]); return j; } Sample Code #include<stdio.h> #include<conio.h> int Partition(int a[],int m,int p); void Interchange(int a[],int i,int j); int a[100]; void QuickSort(int p,int q) { int j; if(p<q) { j=Partition(a,p,q+1); QuickSort(p,j-1); QuickSort(j+1,q); } } int Partition(int a[],int m,int p) { int pivot,j,i; pivot=a[m],i=m,j=p; do {
  • 20. do { i++; }while(a[i]<=pivot); do { j--; }while(a[j]>pivot); if(i<j) Interchange(a,i,j); }while(i<=j); a[m]=a[j]; a[j]=pivot; return j; } void Interchange(int a[],int i,int j) { int p; p=a[i]; a[i]=a[j]; a[j]=p; } int main() { int k,n,c=1,temp; printf("Enter the range of arrayn"); scanf("%d",&n); printf("Enter an infinite numbern"); scanf("%d",&temp); printf("Input the arrayn"); for(k=1;k<=n;k++)
  • 21. scanf("%d",&a[k]); a[n+1]=temp; QuickSort(c,n); printf("Output arrayn"); for(k=1;k<=n;k++) printf("%dt",a[k]); return 0; } Sample Output Enter the range of array 7 Enter an infinite number 100000 Input the array 6 7 5 6 0 0 3 Output array 0 0 3 5 6 6 7