0% found this document useful (0 votes)
5 views23 pages

Insertion and Bubble Sort in C

The document contains two sorting algorithms implemented in C: insertion sort and bubble sort. Each algorithm includes a function to sort an array and a function to print the sorted array. Example arrays are provided in the main function to demonstrate the sorting process.

Uploaded by

suddugunjal
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)
5 views23 pages

Insertion and Bubble Sort in C

The document contains two sorting algorithms implemented in C: insertion sort and bubble sort. Each algorithm includes a function to sort an array and a function to print the sorted array. Example arrays are provided in the main function to demonstrate the sorting process.

Uploaded by

suddugunjal
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

SORTING

CODE

#include <math.h>
#include <stdio.h>

void insertionSort(int arr[], int n)


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

void printArray(int arr[], int n)


{ int

i;

for (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);
printArray(arr, n); return 0;
}

OUTPUT
CODE
#include <stdio.h>

void swap(int* arr, int i, int j)


{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

void bubbleSort(int arr[], int n)


{ int i,
j;

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


for (j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1])
swap(arr, j, j + 1);
}

void printArray(int arr[], int size)


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

int main()
{
int arr[] = { 5, 1, 4, 2, 8 }; int N =
sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, N);
printf("Sorted array: ");
printArray(arr, N); return 0;
}

OUTPUT

You might also like