Name 1
Name 1
Roll – 35000120025
Department – CSE
Code –
#include<stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n-1; i++)
{
swapped = false;
for (j = 0; j < n-i-1; j++)
{
if (arr[j] > arr[j+1])
{
swap(&arr[j], &arr[j+1]);
swapped = true;
}
}
}
}
int main()
{
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array: \n");
for(int i = 0 ; i < n ; i++){
printf("%d ", arr[i]);
}
return 0;
}
Flowchart -
2. Write down the C code for implementing insertion
sort in an array of n natural numbers.
Algorithm
The simple steps of achieving the insertion sort are listed as follows -
Step3 - Now, compare the key with all elements in the sorted array.
Step 4 - If the element in the sorted array is smaller than the current
element, then move to the next element. Else, shift greater elements in
the array towards the right.
Code –
#include <math.h>
#include <stdio.h>
insertionSort(arr, n);
for(int i = 0; i < n; i++){
printf("%d ",arr[i]);
}
return 0;
}
Flowchart -