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

Similar to Sorting Algorithms and their implementations (20)

PDF
Heap, quick and merge sort
Dr. Mohammad Amir Khusru Akhtar (Ph.D)
 
PPT
Lec 6 Divide and conquer of Data Structures & Algortihms
haseebanjum2611
 
PPTX
Data Structure and algorithms for software
ManishShukla712917
 
DOCX
DAA Lab Work.docx
Deepusri2000Srivasta
 
PPTX
Weak 11-12 Sorting update.pptxbhjiiuuuuu
baloch4551701
 
PPTX
data structures and algorithms Unit 3
infanciaj
 
PPTX
Merge sort-algorithm for computer science engineering students
University of Science and Technology Chitttagong
 
PPTX
Merge sort algorithm power point presentation
University of Science and Technology Chitttagong
 
PPT
computer notes - Data Structures - 39
ecomputernotes
 
PPT
Computer notes - Mergesort
ecomputernotes
 
PDF
Sorting
A. S. M. Shafi
 
PPTX
Sorting techniques
JayeshGadhave1
 
PDF
Merge sort
Abdelrahman Saleh
 
PPT
Data Structure Sorting
Muhazzab Chouhadry
 
PPT
Lec35
Nikhil Chilwant
 
PPTX
LectureSlidData_sturcture_algorithm_v2.pptx
abhaysharma999437
 
PPTX
2.Problem Solving Techniques and Data Structures.pptx
Ganesh Bhosale
 
DOCX
DAA Lab File C Programs
Kandarp Tiwari
 
Heap, quick and merge sort
Dr. Mohammad Amir Khusru Akhtar (Ph.D)
 
Lec 6 Divide and conquer of Data Structures & Algortihms
haseebanjum2611
 
Data Structure and algorithms for software
ManishShukla712917
 
DAA Lab Work.docx
Deepusri2000Srivasta
 
Weak 11-12 Sorting update.pptxbhjiiuuuuu
baloch4551701
 
data structures and algorithms Unit 3
infanciaj
 
Merge sort-algorithm for computer science engineering students
University of Science and Technology Chitttagong
 
Merge sort algorithm power point presentation
University of Science and Technology Chitttagong
 
computer notes - Data Structures - 39
ecomputernotes
 
Computer notes - Mergesort
ecomputernotes
 
Sorting techniques
JayeshGadhave1
 
Merge sort
Abdelrahman Saleh
 
Data Structure Sorting
Muhazzab Chouhadry
 
LectureSlidData_sturcture_algorithm_v2.pptx
abhaysharma999437
 
2.Problem Solving Techniques and Data Structures.pptx
Ganesh Bhosale
 
DAA Lab File C Programs
Kandarp Tiwari
 

Recently uploaded (20)

PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PDF
AI-assisted IP-Design lecture from the MIPLM 2025
MIPLM
 
PDF
Introduction presentation of the patentbutler tool
MIPLM
 
PPTX
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
PPTX
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
PPT
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
PPTX
How to Configure Refusal of Applicants in Odoo 18 Recruitment
Celine George
 
PDF
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
PPTX
GENERAL BIOLOGY 1 - Subject Introduction
marvinnbustamante1
 
DOCX
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
PDF
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
PPTX
Different types of inheritance in odoo 18
Celine George
 
PPTX
How to Manage Expiry Date in Odoo 18 Inventory
Celine George
 
PPTX
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
PDF
Lesson 1 - Nature of Inquiry and Research.pdf
marvinnbustamante1
 
PDF
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
AI-assisted IP-Design lecture from the MIPLM 2025
MIPLM
 
Introduction presentation of the patentbutler tool
MIPLM
 
Aerobic and Anaerobic respiration and CPR.pptx
Olivier Rochester
 
Building Powerful Agentic AI with Google ADK, MCP, RAG, and Ollama.pptx
Tamanna36
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Our Guide to the July 2025 USPS® Rate Change
Postal Advocate Inc.
 
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
How to Configure Refusal of Applicants in Odoo 18 Recruitment
Celine George
 
I3PM Industry Case Study Siemens on Strategic and Value-Oriented IP Management
MIPLM
 
GENERAL BIOLOGY 1 - Subject Introduction
marvinnbustamante1
 
Lesson 1 - Nature and Inquiry of Research
marvinnbustamante1
 
Indian National movement PPT by Simanchala Sarab, Covering The INC(Formation,...
Simanchala Sarab, BABed(ITEP Secondary stage) in History student at GNDU Amritsar
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
How to Add a Custom Button in Odoo 18 POS Screen
Celine George
 
Different types of inheritance in odoo 18
Celine George
 
How to Manage Expiry Date in Odoo 18 Inventory
Celine George
 
Marketing Management PPT Unit 1 and Unit 2.pptx
Sri Ramakrishna College of Arts and science
 
Lesson 1 - Nature of Inquiry and Research.pdf
marvinnbustamante1
 
TLE 8 QUARTER 1 MODULE WEEK 1 MATATAG CURRICULUM
denniseraya1997
 
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); }