SlideShare a Scribd company logo
Sorting
• Arranging the data in a logical order
•
• Ascending order is a method of arranging numbers from smallest
value to largest value.
• OR
• Descending order is a method of arranging numbers from largest
value to smallest value.
Different sorting techniques
• Insertion sort
• Selection sort
• Bubble sort
• Merge sort
• Quick sort
Insertion Sort
Algorithm
• Step 1 − If the element is the first one, it is already sorted.
• Step 2 – Move to next element
• Step 3 − Compare the current element with all elements in
the sorted array
• Step 4 – If the element in the sorted array is smaller than the
current element, iterate to the next element. Otherwise, shift
all the greater element in the array by one position towards
the right
• Step 5 − Insert the value at the correct position
• Step 6 − Repeat until the complete list is sorted
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Code
void insertionSort(int array[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = array[i];
j = i - 1;
while (j >= 0 && array[j] > key)
{
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = key;
}
}
Selection Sort
Algorithm
• Step 1 − Set MIN to location 0
• Step 2 − Search the minimum element in the list
• Step 3 − Swap with value at location MIN
• Step 4 − Increment MIN to point to next element
• Step 5 − Repeat until list is sorted
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
#include <stdio.h>
int main()
{
int arr[10]={6,12,0,18,11,99,55,45,34,2};
int n=10;
int i, j, min, swap;
for (i = 0; i < (n - 1); i++)
{
min = i;
for (j = i + 1; j < n; j++)
{
if (arr[min] > arr[j])
min = j;
}
if (min != i)
{
swap = arr[i];
arr[i] = arr[min];
arr[min] = swap;
}
}
for (i = 0; i < n; i++)
printf("%dt", arr[i]);
return 0;
}
Merge Sort
Divide and Conquer
• Merge Sort is one of the most popular sorting algorithms that is
based on the principle of Divide and Conquer Algorithm.
• Here, a problem is divided into multiple sub-problems. Each sub-
problem is solved individually. Finally, sub-problems are combined to
form the final solution.
• Strategy
• Using the Divide and Conquer technique, we divide a problem into
subproblems. When the solution to each subproblem is ready, we 'combine'
the results from the subproblems to solve the main problem.
Sorting Algorithms and their implementations
Step 1: Create duplicate copies of sub-arrays to be sorted
// Create L ← A[l..m] and R ← A[m+1..r]
int n1 = m - l + 1 = 3 - 0 + 1 = 4;
int n2 = r - m = 5 - 3 = 2;
int L[4], R[2];
for (int i = 0; i < 4; i++)
L[i] = arr[l + i];
// L[0,1,2,3] = A[0,1,2,3] = [1,5,10,12]
for (int j = 0; j < 2; j++)
R[j] = arr[m + 1 + j];
// R[0,1] = A[4,5] = [6,9]
A
L
R
Step 2: Maintain current index of sub-arrays and main array
int i, j, k;
i = 0;
j = 0;
k = l;
Step 3: Until we reach the end of either L or R, pick smaller
among elements L and R and place them in the correct
position at A[l..m]
while (i < n1 && j < n2)
{
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}
Step 4: When we run out of elements in either L or R, pick up
the remaining elements and put in A[l..m]
// We exited the earlier loop because j < n2 doesn't hold
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
Cont..
// We exited the earlier loop because i < n1 doesn't hold
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// C program for Merge Sort
#include <stdio.h>
#include <stdlib.h>
// Merges two subarrays of arr[].
// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int arr[], int l,int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
// Create temp arrays
int L[n1], R[n2];
// Copy data to temp arrays
// L[] and R[]
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
// Merge the temp arrays back
// into arr[l..r]
// Initial index of first subarray
i = 0;
// Initial index of second subarray
j = 0;
// Initial index of merged subarray
k = l;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
// Copy the remaining elements
// of L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy the remaining elements of
// R[], if there are any
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
// l is for left index and r is
// right index of the sub-array
// of arr to be sorted
• void mergeSort(int arr[],int l, int r)
• {
• if (l < r)
• {
• // Same as (l+r)/2, but avoids
• // overflow for large l and h
• int m = l + (r - l) / 2;
•
• // Sort first and second halves
• mergeSort(arr, l, m);
• mergeSort(arr, m + 1, r);
•
• merge(arr, l, m, r);
• }
• }
Sorting Algorithms and their implementations
Merge 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.
1. Select the Pivot Element
2. Rearrange the Array
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
3. Divide Subarrays
• Pivot elements are again chosen for the left and the right sub-parts
separately. And, step 2 is repeated.
Sorting Algorithms and their implementations
Sorting Algorithms and their implementations
// Quick sort in C
#include <stdio.h>
// function to swap elements
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
// function to find the partition position
int partition(int array[], int low, int high) {
// select the rightmost element as pivot
int pivot = array[high];
// pointer for greater element
int i = (low - 1);
// traverse each element of the array
// compare them with the pivot
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
// if element smaller than pivot is found
// swap it with the greater element pointed by i
i++;
// swap element at i with element at j
swap(&array[i], &array[j]);
}
}
// swap the pivot element with the greater
element at i
swap(&array[i + 1], &array[high]);
// return the partition point
return (i + 1);
}
void quickSort(int array[], int low, int high) {
if (low < high) {
// find the pivot element such that
// elements smaller than pivot are on left of pivot
// elements greater than pivot are on right of pivot
int pi = partition(array, low, high);
// recursive call on the left of pivot
quickSort(array, low, pi - 1);
// recursive call on the right of pivot
quickSort(array, pi + 1, high);
}
}
// function to print array elements
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("n");
}
// main function
int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
int n = sizeof(data) / sizeof(data[0]);
printf("Unsorted Arrayn");
printArray(data, n);
// perform quicksort on data
quickSort(data, 0, n - 1);
printf("Sorted array in ascending order: n");
printArray(data, n);
}

More Related Content

PPT
DAA-Divide and Conquer methodology, DAA 2024
RUHULAMINHAZARIKA
 
PPTX
Searching and Sorting Algorithms in Data Structures
poongothai11
 
PPTX
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
VISWANATHAN R V
 
PPTX
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
kncetaruna
 
DOCX
DAA Lab Work.docx
Deepusri2000Srivasta
 
PPTX
Sorting techniques
JayeshGadhave1
 
PPTX
searching in data structure.pptx
chouguleamruta24
 
PPTX
data structures and algorithms Unit 3
infanciaj
 
DAA-Divide and Conquer methodology, DAA 2024
RUHULAMINHAZARIKA
 
Searching and Sorting Algorithms in Data Structures
poongothai11
 
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
VISWANATHAN R V
 
UNIT V Searching Sorting Hashing Techniques [Autosaved].pptx
kncetaruna
 
DAA Lab Work.docx
Deepusri2000Srivasta
 
Sorting techniques
JayeshGadhave1
 
searching in data structure.pptx
chouguleamruta24
 
data structures and algorithms Unit 3
infanciaj
 

Similar to Sorting Algorithms and their implementations (20)

PDF
Sorting algorithms bubble sort to merge sort.pdf
AyeshaMazhar21
 
PPTX
Dsa – data structure and algorithms sorting
sajinis3
 
PPT
3.8 quick sort
Krish_ver2
 
PPTX
Searching and Sorting algorithms and working
RitikaLohiya2
 
PPT
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
Kanupriya731200
 
PPT
search_sort Search sortSearch sortSearch sortSearch sort
Shanmuganathan C
 
PPTX
Chapter 2 Sorting and Searching .pptx.soft
kuruabeje7
 
PPTX
Sorting pnk
pinakspatel
 
PPT
search_sort_v1.pptgghghhhggggjjjjjjllllllllvbbbbbcfdsdfffg
arpitasahad87
 
PDF
Searching, Sorting and Complexity analysis in DS.pdf
AkshatMehrotra14
 
PPTX
sorting and searching.pptx
ParagAhir1
 
PPTX
Data analysis and algorithms - UNIT 2.pptx
sgrishma559
 
PDF
Heap, quick and merge sort
Dr. Mohammad Amir Khusru Akhtar (Ph.D)
 
PPTX
Data structures
Sneha Chopra
 
PPTX
Unit III Version I.pptx
ssuserd602fd
 
PPTX
AJisthewewrtyuiojhghfdfsgvhjhklopi87ytrytfghjk
PradipTadme
 
PDF
Quicksort AlgorithmQuicksort is a divide and conquer algorithm. Q.pdf
anupamfootwear
 
PDF
DSA Lec 5+6(Search+Sort) (1).pdf
MustafaJutt4
 
PPTX
Divide and Conquer
Melaku Bayih Demessie
 
PPT
search_sort.ppt
SwatiHans10
 
Sorting algorithms bubble sort to merge sort.pdf
AyeshaMazhar21
 
Dsa – data structure and algorithms sorting
sajinis3
 
3.8 quick sort
Krish_ver2
 
Searching and Sorting algorithms and working
RitikaLohiya2
 
search_sort search_sortsearch_sort search_sortsearch_sortsearch_sortsearch_sort
Kanupriya731200
 
search_sort Search sortSearch sortSearch sortSearch sort
Shanmuganathan C
 
Chapter 2 Sorting and Searching .pptx.soft
kuruabeje7
 
Sorting pnk
pinakspatel
 
search_sort_v1.pptgghghhhggggjjjjjjllllllllvbbbbbcfdsdfffg
arpitasahad87
 
Searching, Sorting and Complexity analysis in DS.pdf
AkshatMehrotra14
 
sorting and searching.pptx
ParagAhir1
 
Data analysis and algorithms - UNIT 2.pptx
sgrishma559
 
Heap, quick and merge sort
Dr. Mohammad Amir Khusru Akhtar (Ph.D)
 
Data structures
Sneha Chopra
 
Unit III Version I.pptx
ssuserd602fd
 
AJisthewewrtyuiojhghfdfsgvhjhklopi87ytrytfghjk
PradipTadme
 
Quicksort AlgorithmQuicksort is a divide and conquer algorithm. Q.pdf
anupamfootwear
 
DSA Lec 5+6(Search+Sort) (1).pdf
MustafaJutt4
 
Divide and Conquer
Melaku Bayih Demessie
 
search_sort.ppt
SwatiHans10
 
Ad

Recently uploaded (20)

PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPTX
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PDF
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
PPTX
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
PDF
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
PPTX
Autodock-for-Beginners by Rahul D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PDF
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
FSSAI (Food Safety and Standards Authority of India) & FDA (Food and Drug Adm...
Dr. Paindla Jyothirmai
 
PPTX
CDH. pptx
AneetaSharma15
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Introduction to pediatric nursing in 5th Sem..pptx
AneetaSharma15
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PG-BPSDMP 2 TAHUN 2025PG-BPSDMP 2 TAHUN 2025.pdf
AshifaRamadhani
 
CONCEPT OF CHILD CARE. pptx
AneetaSharma15
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
The Picture of Dorian Gray summary and depiction
opaliyahemel
 
Autodock-for-Beginners by Rahul D Jawarkar.pptx
Rahul Jawarkar
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
The Minister of Tourism, Culture and Creative Arts, Abla Dzifa Gomashie has e...
nservice241
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
FSSAI (Food Safety and Standards Authority of India) & FDA (Food and Drug Adm...
Dr. Paindla Jyothirmai
 
CDH. pptx
AneetaSharma15
 
Ad

Sorting Algorithms and their implementations

  • 2. • Arranging the data in a logical order • • Ascending order is a method of arranging numbers from smallest value to largest value. • OR • Descending order is a method of arranging numbers from largest value to smallest value.
  • 3. Different sorting techniques • Insertion sort • Selection sort • Bubble sort • Merge sort • Quick sort
  • 5. Algorithm • Step 1 − If the element is the first one, it is already sorted. • Step 2 – Move to next element • Step 3 − Compare the current element with all elements in the sorted array • Step 4 – If the element in the sorted array is smaller than the current element, iterate to the next element. Otherwise, shift all the greater element in the array by one position towards the right • Step 5 − Insert the value at the correct position • Step 6 − Repeat until the complete list is sorted
  • 11. Code void insertionSort(int array[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = array[i]; j = i - 1; while (j >= 0 && array[j] > key) { array[j + 1] = array[j]; j = j - 1; } array[j + 1] = key; } }
  • 13. Algorithm • Step 1 − Set MIN to location 0 • Step 2 − Search the minimum element in the list • Step 3 − Swap with value at location MIN • Step 4 − Increment MIN to point to next element • Step 5 − Repeat until list is sorted
  • 19. #include <stdio.h> int main() { int arr[10]={6,12,0,18,11,99,55,45,34,2}; int n=10; int i, j, min, swap; for (i = 0; i < (n - 1); i++) { min = i; for (j = i + 1; j < n; j++) { if (arr[min] > arr[j]) min = j; }
  • 20. if (min != i) { swap = arr[i]; arr[i] = arr[min]; arr[min] = swap; } } for (i = 0; i < n; i++) printf("%dt", arr[i]); return 0; }
  • 22. Divide and Conquer • Merge Sort is one of the most popular sorting algorithms that is based on the principle of Divide and Conquer Algorithm. • Here, a problem is divided into multiple sub-problems. Each sub- problem is solved individually. Finally, sub-problems are combined to form the final solution. • Strategy • Using the Divide and Conquer technique, we divide a problem into subproblems. When the solution to each subproblem is ready, we 'combine' the results from the subproblems to solve the main problem.
  • 24. Step 1: Create duplicate copies of sub-arrays to be sorted // Create L ← A[l..m] and R ← A[m+1..r] int n1 = m - l + 1 = 3 - 0 + 1 = 4; int n2 = r - m = 5 - 3 = 2; int L[4], R[2]; for (int i = 0; i < 4; i++) L[i] = arr[l + i]; // L[0,1,2,3] = A[0,1,2,3] = [1,5,10,12] for (int j = 0; j < 2; j++) R[j] = arr[m + 1 + j]; // R[0,1] = A[4,5] = [6,9] A L R
  • 25. Step 2: Maintain current index of sub-arrays and main array int i, j, k; i = 0; j = 0; k = l;
  • 26. Step 3: Until we reach the end of either L or R, pick smaller among elements L and R and place them in the correct position at A[l..m] while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; }
  • 27. Step 4: When we run out of elements in either L or R, pick up the remaining elements and put in A[l..m] // We exited the earlier loop because j < n2 doesn't hold while (i < n1) { arr[k] = L[i]; i++; k++; }
  • 28. Cont.. // We exited the earlier loop because i < n1 doesn't hold while (j < n2) { arr[k] = R[j]; j++; k++; } }
  • 29. // C program for Merge Sort #include <stdio.h> #include <stdlib.h> // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l,int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; // Create temp arrays int L[n1], R[n2]; // Copy data to temp arrays // L[] and R[] for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; // Merge the temp arrays back // into arr[l..r] // Initial index of first subarray i = 0; // Initial index of second subarray j = 0; // Initial index of merged subarray k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } // Copy the remaining elements // of L[], if there are any while (i < n1) { arr[k] = L[i]; i++; k++; } // Copy the remaining elements of // R[], if there are any while (j < n2) { arr[k] = R[j]; j++; k++; } } // l is for left index and r is // right index of the sub-array // of arr to be sorted
  • 30. • void mergeSort(int arr[],int l, int r) • { • if (l < r) • { • // Same as (l+r)/2, but avoids • // overflow for large l and h • int m = l + (r - l) / 2; • • // Sort first and second halves • mergeSort(arr, l, m); • mergeSort(arr, m + 1, r); • • merge(arr, l, m, r); • } • }
  • 33. • 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.
  • 34. 1. Select the Pivot Element
  • 42. 3. Divide Subarrays • Pivot elements are again chosen for the left and the right sub-parts separately. And, step 2 is repeated.
  • 45. // Quick sort in C #include <stdio.h> // function to swap elements void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; }
  • 46. // function to find the partition position int partition(int array[], int low, int high) { // select the rightmost element as pivot int pivot = array[high]; // pointer for greater element int i = (low - 1); // traverse each element of the array // compare them with the pivot for (int j = low; j < high; j++) { if (array[j] <= pivot) { // if element smaller than pivot is found // swap it with the greater element pointed by i i++; // swap element at i with element at j swap(&array[i], &array[j]); } } // swap the pivot element with the greater element at i swap(&array[i + 1], &array[high]); // return the partition point return (i + 1); }
  • 47. void quickSort(int array[], int low, int high) { if (low < high) { // find the pivot element such that // elements smaller than pivot are on left of pivot // elements greater than pivot are on right of pivot int pi = partition(array, low, high); // recursive call on the left of pivot quickSort(array, low, pi - 1); // recursive call on the right of pivot quickSort(array, pi + 1, high); } }
  • 48. // function to print array elements void printArray(int array[], int size) { for (int i = 0; i < size; ++i) { printf("%d ", array[i]); } printf("n"); } // main function int main() { int data[] = {8, 7, 2, 1, 0, 9, 6}; int n = sizeof(data) / sizeof(data[0]); printf("Unsorted Arrayn"); printArray(data, n); // perform quicksort on data quickSort(data, 0, n - 1); printf("Sorted array in ascending order: n"); printArray(data, n); }