0% found this document useful (0 votes)
25 views25 pages

Searching Types of Sorting

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

Searching Types of Sorting

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

Searching Types of Sorting

Sorting Algorithms in C
Sorting algorithms are used to arrange elements of an array or list in a specific order
(ascending or descending).

Types of Sorting Algorithms

Sorting algorithms can be broadly classified into two categories:

1. Internal Sorting: Sorting takes place entirely in main memory.


a. Examples: Bubble Sort, Selection Sort, Insertion Sort.
2. External Sorting: Sorting involves large data that cannot fit entirely into memory.
a. Examples: Merge Sort, External Merge Sort.

1. Bubble Sort

Definition: Bubble Sort is a simple comparison-based algorithm where adjacent elements


are compared, and they are swapped if they are in the wrong order.

Syntax

for (int i = 0; i < n-1; i++) {


for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
}
}
}
Program

#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

2. Selection Sort

Definition: This algorithm divides the array into a sorted and an unsorted part. The
smallest element from the unsorted part is selected and swapped with the first unsorted
element.

Syntax

for (int i = 0; i < n-1; i++) {

int min_idx = i;

for (int j = i+1; j < n; j++) {


if (arr[j] < arr[min_idx]) min_idx = j;

// Swap arr[min_idx] and arr[i]

Program
#include <stdio.h>

void selectionSort(int arr[], int n) {

for (int i = 0; i < n - 1; i++) {

int min_idx = i;

for (int j = i + 1; j < n; j++)

if (arr[j] < arr[min_idx])

min_idx = j;

// Swap

int temp = arr[min_idx];

arr[min_idx] = arr[i];

arr[i] = temp;

void printArray(int arr[], int n) {

for (int i = 0; i < n; i++) printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[] = {64, 25, 12, 22, 11};

int n = sizeof(arr) / sizeof(arr[0]);

selectionSort(arr, n);
printf("Sorted array: ");

printArray(arr, n);

return 0;

3. Insertion Sort

Definition: Builds the final sorted array one item at a time by inserting unsorted items into
their correct position.

Syntax

for (int i = 1; i < n; i++) {

int key = arr[i];

int j = i - 1;

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j--;

arr[j + 1] = key;

Program

#include <stdio.h>

void insertionSort(int arr[], int n) {

for (int i = 1; i < n; i++) {

int key = arr[i];


int j = i - 1;

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j--;

arr[j + 1] = key;

void printArray(int arr[], int n) {

for (int i = 0; i < n; i++) printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[] = {12, 11, 13, 5, 6};

int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

printf("Sorted array: ");

printArray(arr, n);

return 0;

4. Quick Sort

Definition: A divide-and-conquer algorithm. A pivot element is chosen, and the array is


partitioned such that elements less than the pivot are on one side, and those greater are
on the other side.
Syntax

void quickSort(int arr[], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

Program

#include <stdio.h>

int partition(int arr[], int low, int high) {

int pivot = arr[high];

int i = (low - 1);

for (int j = low; j <= high - 1; j++) {

if (arr[j] < pivot) {

i++;

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

int temp = arr[i + 1];

arr[i + 1] = arr[high];

arr[high] = temp;
return (i + 1);

void quickSort(int arr[], int low, int high) {

if (low < high) {

int pi = partition(arr, low, high);

quickSort(arr, low, pi - 1);

quickSort(arr, pi + 1, high);

void printArray(int arr[], int size) {

for (int i = 0; i < size; i++) printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[] = {10, 7, 8, 9, 1, 5};

int n = sizeof(arr) / sizeof(arr[0]);

quickSort(arr, 0, n - 1);

printf("Sorted array: ");

printArray(arr, n);

return 0;

5. Merge Sort

Definition: A divide-and-conquer algorithm that divides the array into halves, recursively
sorts them, and merges the sorted halves.
Syntax

void mergeSort(int arr[], int l, int r) {

if (l < r) {

int m = l + (r - l) / 2;

mergeSort(arr, l, m);

mergeSort(arr, m + 1, r);

merge(arr, l, m, r);

Program

#include <stdio.h>

void merge(int arr[], int l, int m, int r) {

int n1 = m - l + 1;

int n2 = r - m;

int L[n1], R[n2];

for (int i = 0; i < n1; i++) L[i] = arr[l + i];

for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];

int i = 0, j = 0, k = l;

while (i < n1 && j < n2) {

if (L[i] <= R[j]) arr[k++] = L[i++];

else arr[k++] = R[j++];

while (i < n1) arr[k++] = L[i++];

while (j < n2) arr[k++] = R[j++];


}

void mergeSort(int arr[], int l, int r) {

if (l < r) {

int m = l + (r - l) / 2;

mergeSort(arr, l, m);

mergeSort(arr, m + 1, r);

merge(arr, l, m, r);

void printArray(int arr[], int n) {

for (int i = 0; i < n; i++) printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[] = {12, 11, 13, 5, 6, 7};

int n = sizeof(arr) / sizeof(arr[0]);

mergeSort(arr, 0, n - 1);

printf("Sorted array: ");

printArray(arr, n);

return 0;

Here’s a comprehensive guide on sorting algorithms in C covering their types,


explanations, definitions, example programs, and syntax:
Sorting Algorithms in C
Sorting algorithms are used to arrange elements of an array or list in a specific order
(ascending or descending).

Types of Sorting Algorithms

Sorting algorithms can be broadly classified into two categories:

1. Internal Sorting: Sorting takes place entirely in main memory.


a. Examples: Bubble Sort, Selection Sort, Insertion Sort.
2. External Sorting: Sorting involves large data that cannot fit entirely into memory.
a. Examples: Merge Sort, External Merge Sort.

1. Bubble Sort

Definition: Bubble Sort is a simple comparison-based algorithm where adjacent elements


are compared, and they are swapped if they are in the wrong order.

Syntax

c
Copy code
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
// Swap arr[j] and arr[j+1]
}
}
}

Program

#include <stdio.h>
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

2. Selection Sort

Definition: This algorithm divides the array into a sorted and an unsorted part. The
smallest element from the unsorted part is selected and swapped with the first unsorted
element.

Syntax

for (int i = 0; i < n-1; i++) {


int min_idx = i;
for (int j = i+1; j < n; j++) {
if (arr[j] < arr[min_idx]) min_idx = j;
}
// Swap arr[min_idx] and arr[i]
}

Program

#include <stdio.h>
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
int min_idx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

3. Insertion Sort

Definition: Builds the final sorted array one item at a time by inserting unsorted items into
their correct position.
Syntax

for (int i = 1; i < n; i++) {


int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}

Program

#include <stdio.h>
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

4. Quick Sort

Definition: A divide-and-conquer algorithm. A pivot element is chosen, and the array is


partitioned such that elements less than the pivot are on one side, and those greater are
on the other side.

Syntax

void quickSort(int arr[], int low, int high) {


if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}

Program

#include <stdio.h>
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}

5. Merge Sort

Definition: A divide-and-conquer algorithm that divides the array into halves, recursively
sorts them, and merges the sorted halves.

Syntax

void mergeSort(int arr[], int l, int r) {


if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
Program

#include <stdio.h>
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (int i = 0; i < n1; i++) L[i] = arr[l + i];
for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) arr[k++] = L[i++];
else arr[k++] = R[j++];
}
while (i < n1) arr[k++] = L[i++];
while (j < n2) arr[k++] = R[j++];
}
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l + (r - l) / 2;
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
printf("\n");
}
int main() {
int arr[] = {12, 11, 13, 5, 6, 7};
int n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1);
printf("Sorted array: ");
printArray(arr, n);
return 0;
}
Comparison of Sorting Algorithms

Best Worst Space


Algorithm Stable
Case Case Complexity
Bubble Sort O(n) O(n²) O(1) Yes
Selection
O(n²) O(n²) O(1) No
Sort
Insertion Sort O(n) O(n²) O(1) Yes
Quick Sort O(n log n) O(n²) O(log n) No
Merge Sort O(n log n) O(n log n) O(n) Yes

Theoretical Questions

1. What is Sorting?

Answer:

Sorting is the process of arranging elements in a specific order (either ascending or


descending). It improves the efficiency of search operations and helps in data
organization.

2. What are the types of sorting?

Answer:

The two main types are:

1. Internal Sorting: Sorting done in memory (e.g., Bubble Sort, Quick Sort).
2. External Sorting: Sorting large data stored in external storage (e.g., Merge Sort with
external files).
3. What is the difference between stable and unstable sorting algorithms?

Answer:

• Stable Sorting: Maintains the relative order of equal elements (e.g., Bubble Sort,
Merge Sort).
• Unstable Sorting: May not maintain the relative order of equal elements (e.g.,
Quick Sort, Heap Sort).

4. Explain the time complexities of sorting algorithms.

Answer:

Best Average Worst


Algorithm
Case Case Case
Bubble Sort O(n) O(n²) O(n²)
Quick Sort O(n log n) O(n log n) O(n²)
Merge Sort O(n log n) O(n log n) O(n log n)
Heap Sort O(n log n) O(n log n) O(n log n)
Radix Sort O(nk) O(nk) O(nk)

5. Why is Quick Sort faster than Merge Sort in practice?

Answer:

Quick Sort is faster for small datasets because of its in-place sorting mechanism and
lower constant factors in runtime. Merge Sort requires additional memory for merging.

6. Which sorting algorithm is best for nearly sorted data?

Answer:

Insertion Sort is best for nearly sorted data due to its low overhead and O(n) complexity in
the best case.
7. What is the advantage of Merge Sort over Quick Sort?

Answer:

Merge Sort is stable and has a guaranteed O(n log n) complexity for all cases, making it
suitable for large datasets and external sorting.

8. Can Bubble Sort be used in real-world applications?

Answer:

Bubble Sort is not efficient for large datasets and is mostly used for educational purposes
or when the dataset size is very small.

9. What is the role of the pivot element in Quick Sort?

Answer:

The pivot element partitions the array into two sub-arrays:

• Elements smaller than the pivot.


• Elements greater than the pivot.

This ensures the pivot is placed at its correct sorted position.

10. What is the difference between Radix Sort and Bucket Sort?

Answer:

• Radix Sort: Works digit by digit, using counting sort as a subroutine.


• Bucket Sort: Divides data into buckets and sorts each bucket individually using
another sorting algorithm.
1. Explain Bubble Sort with its algorithm, working,
advantages, and disadvantages.

Answer:

Bubble Sort:

Bubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares
adjacent elements, and swaps them if they are in the wrong order. The process is repeated
until the list is sorted.

Algorithm:

1. Start with the first element of the array.


2. Compare the current element with the next element.
3. If the current element is greater than the next element, swap them.
4. Repeat the process for all elements of the array.
5. Repeat steps 1–4 for all elements except the last one.
6. Stop when no swaps are needed in a pass.

Working:

• Given an array: [5, 2, 9, 1, 5, 6]


• First pass: [2, 5, 1, 5, 6, 9]
• Second pass: [2, 1, 5, 5, 6, 9]
• Third pass: [1, 2, 5, 5, 6, 9]
• Array is now sorted.

Advantages:

1. Simple to implement.
2. Best case (already sorted array) has a time complexity of O(n).
Disadvantages:

1. Highly inefficient for large datasets.


2. Time complexity in the worst case is O(n²).

2. Explain Quick Sort in detail with its algorithm, working


example, and time complexity analysis.

Answer:

Quick Sort:

Quick Sort is a divide-and-conquer algorithm that partitions the array into sub-arrays and
sorts them independently.

Algorithm:

1. Choose a pivot element from the array.


2. Partition the array such that elements less than the pivot are on the left, and
elements greater than the pivot are on the right.
3. Recursively apply Quick Sort to the sub-arrays.

Working Example:

• Array: [10, 7, 8, 9, 1, 5]
1. Pivot = 5. Partition: [1] [5] [10, 7, 8, 9].
2. Recursively sort left: [1].
3. Recursively sort right: [7, 8, 9, 10].

Final sorted array: [1, 5, 7, 8, 9, 10].

Time Complexity:

• Best Case: O(n log n) when the pivot divides the array into two equal parts.
• Worst Case: O(n²) when the smallest or largest element is chosen as the pivot.
• Average Case: O(n log n).
3. Write a detailed note on Merge Sort, including its
working mechanism, advantages, and disadvantages.

Answer:

Merge Sort:

Merge Sort is a divide-and-conquer algorithm that divides the array into two halves,
recursively sorts them, and merges the sorted halves.

Algorithm:

1. Divide the array into two halves.


2. Recursively sort the left and right halves.
3. Merge the sorted halves into a single sorted array.

Working Example:

• Array: [12, 11, 13, 5, 6, 7]


1. Divide: [12, 11, 13] and [5, 6, 7].
2. Recursively sort left: [11, 12, 13].
3. Recursively sort right: [5, 6, 7].
4. Merge: [5, 6, 7, 11, 12, 13].

Advantages:

1. Stable sorting algorithm.


2. Consistent time complexity of O(n log n).
3. Suitable for large datasets and external sorting.

Disadvantages:

1. Requires additional memory for merging (O(n) space complexity).


2. Comparatively slower than Quick Sort for small datasets.
4. Compare and contrast Heap Sort and Merge Sort.

Answer:

Aspect Heap Sort Merge Sort


An in-place, comparison-based A divide-and-conquer algorithm that
Definiti
sorting algorithm using a binary heap splits the array and merges sorted
on
structure. halves.
Stabilit
Not stable Stable
y
Time
Compl O(n log n) in all cases O(n log n) in all cases
exity
Space
Compl O(1) O(n)
exity
Advant Guarantees stability and consistent
Efficient in-place sorting.
ages time complexity.
Disadv
Not suitable for stable sorting
antage Higher memory usage due to merging.
requirements.
s

5. Explain Radix Sort with an example and its time


complexity.

Answer:

Radix Sort:

Radix Sort is a non-comparison-based algorithm that sorts numbers digit by digit.

Working:

1. Group numbers by their least significant digit (LSD).


2. Reorder numbers within groups based on the next significant digit.
3. Repeat until all digits are considered.
Example:

• Array: [170, 45, 75, 90, 802, 24, 2, 66]


1. Sort by LSD: [170, 90, 802, 2, 24, 45, 75, 66].
2. Sort by tens digit: [802, 2, 24, 45, 66, 170, 75, 90].
3. Sort by hundreds digit: [2, 24, 45, 66, 75, 90, 170, 802].

Time Complexity:

• Best, Worst, and Average Case: O(nk), where n is the number of elements and k is
the number of digits.

Advantages:

1. Efficient for large numbers with a fixed range of digits.


2. No comparisons are required.

Disadvantages:

1. Restricted to numerical or fixed-length data.


2. Requires additional memory for buckets.

6. Discuss the practical applications of different sorting


algorithms.

Answer:

Applications:

1. Bubble Sort:
a. Educational purposes (understanding basic sorting concepts).
b. Small datasets.
2. Quick Sort:
a. Efficient sorting in software libraries.
b. Used in scenarios where memory usage needs to be minimized.
3. Merge Sort:
a. External sorting (e.g., large datasets stored on disks).
b. Stable sorting requirements.
4. Heap Sort:
a. Priority queue implementations.
b. Real-time systems due to predictable O(n log n) performance.
5. Radix Sort:
a. Sorting large datasets of fixed-length keys (e.g., phone numbers, IP
addresses).

7. Describe Selection Sort in detail with its algorithm and


drawbacks.

Answer:

Selection Sort:

Selection Sort repeatedly selects the smallest element from the unsorted portion of the
array and swaps it with the first unsorted element.

Algorithm:

1. Find the smallest element in the array.


2. Swap it with the first element.
3. Repeat for the remaining unsorted elements.

Drawbacks:

1. Time complexity of O(n²), making it inefficient for large datasets.


2. Not a stable sorting algorithm.

You might also like