0% found this document useful (0 votes)
5 views

DSA Lab File

Uploaded by

Raj Mehra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

DSA Lab File

Uploaded by

Raj Mehra
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

Lab File

For

Data Structures and Algorithms Lab


Using C

AKIDO College of Engineering


Submitted By. : PUSHP BANSAL. Submitted to
B.Tech CSE 3nd Semester

Registration Number. : 2213091682


Subject Code. : LC-CSE-213G

Index
S.N. Program Page Date Sign
1 WAP to make a menu driven 01/09/23
programme on a linear array
2 WAP to make a menu driven 06/09/23
programme with a linear
linked list with element in
ascending order
3 WAP to demonstrate stack for 8/9/23
conversion of infix to post fix
4 WAP to demonstrate various 13/9/23
operations on a linear queue
5 WAP to demonstrate various 15/9/23
operations on a circular queue
6 WAP to illustrate 20/9/23
implementation of operations
on a BST
7 WAP to illustrate traversal of a 27/9/23
BFS
8 WAP to illustrate traversal of a 29/9/23
DFS
9 WAP to Sort an array of 6/10/23
Integers using Bubble Sort.
10 WAP to Sort an array of 11/10/23
Integers using Selection Sort.
11 WAP to Sort an array of 13/10/23
Integers using Insertion Sort.
12 WAP to Sort an array of 18/10/23
Integers using Radix Sort.
13 WAP to Sort an array of 20/10/23
Integers using Merge Sort.

S.N. Program Page Date Sign


14 WAP to Sort an array of 25/10/23
Integers using Quick Sort.
15 WAP to demonstrate use of 27/10/23
linear search
16 WAP to demonstrate use of 17/11/23
Binary Search
Program 1
Aim:
Write a menu driven program that implements following
operations using separate functions for each using a linear
array:
⚫ insert a new element at end as well as at a given position
⚫ delete an element from a given whose value is given or
whose position is given
⚫ to find location of a given element ⚫ to display elements of a
linear array Code:
#include <stdio.h>

void ins_end(int arr[], int *size, int element); void


ins_pos(int arr[], int *size, int position, int element);
void del_val(int arr[], int *size, int value); void
del_pos(int arr[], int *size, int position); int search(int
arr[], int size, int element); void show(int arr[], int size);

int main()
{ int
arr[100];
int size = 0;
int choice, element, position, value;

do {
printf("\nMenu:\n"); printf("1.
Insert at end\n"); printf("2. Insert at
position\n"); printf("3. Delete by
value\n"); printf("4. Delete by
position\n"); printf("5. Find location of
element\n"); printf("6. Display array\
n"); printf("7. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter element to insert at end:
"); scanf("%d", &element);
ins_end(arr, &size, element); break;
case 2:
printf("Enter position to insert at: ");
scanf("%d", &position); printf("Enter
element to insert: "); scanf("%d",
&element); ins_pos(arr, &size,
position, element); break; case
3:
printf("Enter value to delete:
"); scanf("%d", &value);
del_val(arr, &size, value);
break; case 4:
printf("Enter position to delete:
"); scanf("%d", &position);
del_pos(arr, &size, position);
break; case 5:
printf("Enter element to find: ");
scanf("%d", &element); position =
search(arr, size, element); if
(position != -1) {
printf("Element found at position %d\n", position);
} else {
printf("Element not found in the array\n");
}
break; case 6:
show(arr, size);
break;

case 7:
printf("Exiting the program\n");
break; default:
printf("Invalid choice. Please enter a valid option.\n");
}
} while (choice != 7);//break Condition
return 0;
}
//insert an element at end
void ins_end(int arr[], int *size, int element)
{ arr[*size] = element;
(*size)++;
printf("Element %d inserted at the end.\n", element);
}
//insert at given position
void ins_pos(int arr[], int *size, int position, int element)
{ if (position < 0 || position > *size)
{ printf("Invalid position for insertion.\n");
return;
}
//make space
for (int i = *size; i > position; i--)
{ arr[i] = arr[i - 1];

}
//insert the element
arr[position] = element;
(*size)++;
printf("Element %d inserted at position %d.\n", element,
position);
}
//delete vy value
void del_val(int arr[], int *size, int value)
{ int found = 0;
for (int i = 0; i < *size; i++) {
if (arr[i] == value) {
for (int j = i; j < *size - 1; j++) {
arr[j] = arr[j + 1];
}
(*size)--;
found = 1;
printf("Element %d deleted from the array.\n", value);
break;
}
}
if (!found) {
printf("Element %d not found in the array.\n", value);
}
}
//delete by position
void del_pos(int arr[], int *size, int position) {
if (position < 0 || position >= *size)
{ printf("Invalid position for deletion.\n");
return;
}
//shift remaining
for (int i = position; i < *size - 1; i++)
{ arr[i] = arr[i + 1];
}
(*size)--;
printf("Element at position %d deleted from the array.\n",
position);
}
//search by position
int search(int arr[], int size, int element)
{ for (int i = 0; i < size; i++) { if
(arr[i] == element) { return i;
}
}
return -1; // Element not found
}
//display elements void
show(int arr[], int size)
{ printf("Array elements:
"); for (int i = 0; i < size; i+
+) { printf("%d ", arr[i]);
}
printf("\n");
}

Program 2
Aim:
Write a menu driven programme that maintains a linear linked
list whose elements are stored in a ascending order and
implements the following operations using seperate functions
⚫ insert a new element
⚫ delete an existing element
⚫ search an element ⚫ display all the elements Code:
#include <stdio.h>
#include <stdlib.h>
struct Node { int
data; struct Node
*next;
};
struct Node* createNode(int data);
struct Node* ins_element(struct Node* head, int element);
struct Node* del_element(struct Node* head, int
element); int search(struct Node* head, int element); void
show(struct Node* head);

int main() {
struct Node *head = NULL;
int choice, element, result;

do {
// Display menu
printf("\nWhat would you like to do?:\n");
printf("1. Insert an element in the list\n");
printf("2. Delete an element from the list\n");
printf("3. Search for an element\n");
printf("4. Display the linked list\n"); printf("5.
Quit\n"); printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter element to insert in the linked list:
"); scanf("%d", &element); head =
ins_element(head, element); break; case 2:
printf("Enter element to delete from the list:
"); scanf("%d", &element); head =
del_element(head, element); break;

case 3:
printf("Enter element to search in given list:
"); scanf("%d", &element); result =
search(head, element);
if (result)
printf("Element found in the list.\n");
else
printf("Element not found in the list.\
n"); break; case 4:
show(head); break; case 5:
printf("Exiting the program\n");
break; default:
printf("Invalid choice. Please enter a valid option.\n");
}

} while (choice != 5);


return 0;
}
// create a new node struct Node*
createNode(int data) { struct
Node* newNode = (struct
Node*)malloc(sizeof(struct Node));

if (newNode == NULL) {
printf("Memory allocation failed.\n");
exit(1);
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}
// insert an element into the sorted linked list struct Node*
ins_element(struct Node* head, int element) { struct
Node *newNode = createNode(element); struct Node
*current = head, *prev = NULL; while (current != NULL
&& current->data < element) { prev = current;
current = current->next;
}
if (prev == NULL)
{ newNode->next = head;
head = newNode;
} else {
newNode->next = current; prev-
>next = newNode;

}
printf("Element %d inserted into the linked list.\n", element);
return head;
}
// Function to delete an element from the sorted linked list
struct Node* del_element(struct Node* head, int element)
{ struct Node *current = head, *prev = NULL; while
(current != NULL && current->data != element) { prev =
current; current = current->next;
}
if (current != NULL)
{ if (prev == NULL) {
head = current->next;
} else {
prev->next = current->next;
}
free(current);
printf("Element %d deleted from the list.\n", element);
} else {
printf("Element %d not found in the list.\n", element);
}
return head;
}
// Function to search for an element in the sorted linked
list int search(struct Node* head, int element) { struct
Node* current = head;
while (current != NULL && current->data < element)
{ current = current->next;
}
return (current != NULL && current->data == element);
}
// Function to display all elements of the linked
list void show(struct Node* head) { printf("List
elements: "); struct Node* current = head;
while (current != NULL) { printf("%d ",
current->data); current = current->next;
}
printf("\n");
}
Program 3
Aim:
Write a program to demonstrate the use of stack(implemented
using linear array in converting expression from infix notation to
postfix notation.
Code:
#include<stdio.h>
#include<ctype.h>
char stack[100];
int top = -1; void
push(char x)
{
stack[++top] = x;
}
char pop()
{
if(top == -1)
return -1; else
return stack[top--];
}
int priority(char x)
{ if(x ==
'(')
return 0;
if(x == '+'
|| x == '-')
return 1;
if(x == '*'
|| x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression :
"); scanf("%s",exp); printf("\
n"); e = exp;
printf("The postfix notation to the given infix notation is \n");
while(*e != '\0')
{
if(isalnum(*e))
printf("%c ",*e);
else if(*e == '(')
push(*e); else
if(*e == ')')
{
while((x = pop()) != '(')
printf("%c ", x);
}
else
{
while(priority(stack[top]) >=
priority(*e)) printf("%c ",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c ",pop());
}return 0;
}
Program 4

Aim:
Program to demonstrate the implementation of various
operations on a linear queue represented using a linear array
Code:
#include<stdio.h>
#define n 5 int
main()
{
int queue[n],ch=1,front=0,rear=0,i,j=1,x=n;
printf("Queue using Array");
printf("\n1.Insertion \n2.Deletion \n3.Display \n4.Exit");
while(ch)
{
printf("\nEnter the Choice:");
scanf("%d",&ch); switch(ch)
{
case 1:
if(rear==x)
printf("\n Queue is Full");
else
{
printf("\n Enter no %d:",j++);
scanf("%d",&queue[rear++]);
}
break;
case 2:
if(front==rear)
{
printf("\n Queue is empty");
}
else
{
printf("\n Deleted Element is %d",queue[front++]);
x++;
}
break;
case 3:
printf("\nQueue Elements are:\n ");
if(front==rear)
printf("\n Queue is Empty");
else
{
for(i=front; i<rear; i++)
{
printf("%d",queue[i]);
printf("\n");
}
break;
case 4:
exit(0);
default:
printf("Wrong Choice: please see the options");
}
}
}
return 0;
}
Program 5

Aim:
Program to demonstrate the implementation of various
operations on a circular queue represented using a linear array
Code :
#include <stdio.h>

# define max 6
int queue[max]; // array
declaration int front=-1; int rear=-
1;
// function to insert an element in a circular queue void
enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is
empty
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%max==front) // condition to check queue is
full
{
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at
the rear position.
}
}

// function to delete the element from the queue int


dequeue()
{
if((front==-1) && (rear==-1)) // condition to check queue is
empty
{
printf("\nQueue is underflow..");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d",
queue[front]); front=-1; rear=-1;
}
else
{
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%max;
}
}
// function to display the elements of a queue void
display()
{ int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", queue[i]);
i=(i+1)%max;
}
}
}
int main()
{
int choice=1,x; // variables declaration

while(choice<4 && choice!=0) // while loop


{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice");
scanf("%d", &choice);

switch(choice)
{

case 1:

printf("Enter the element which is to be


inserted"); scanf("%d", &x); enqueue(x);
break; case 2: dequeue(); break;

case 3:
display();

}}
return 0;
}
Program 6
Aim:
Program to illustrate implementation of different operations
on a BST. Code:
#include <stdio.h>
#include <stdlib.h>
struct node
{ int data;
struct node *right_child;
struct node *left_child;
};

struct node* new_node(int x)


{ struct node *temp;
temp = malloc(sizeof(struct
node)); temp->data = x; temp-
>left_child = NULL; temp-
>right_child = NULL;

return temp;
}

struct node* search(struct node * root, int x)


{ if (root == NULL || root->data == x)
return root; else if (x > root->data)
return search(root->right_child, x); else
return search(root->left_child, x);
}
struct node* insert(struct node * root, int x)
{ if (root == NULL) return new_node(x);
else if (x > root->data)
root->right_child = insert(root->right_child, x);
else
root -> left_child = insert(root->left_child, x);
return root;
}
struct node* find_minimum(struct node * root)
{ if (root == NULL) return NULL;
else if (root->left_child != NULL)
return find_minimum(root->left_child);
return root;
}

struct node* delete(struct node * root, int x) {

if (root == NULL)
return NULL; if
(x > root->data)
root->right_child = delete(root->right_child, x);
else if (x < root->data)
root->left_child = delete(root->left_child, x);
else {
if (root->left_child == NULL && root->right_child == NULL)
{ free(root); return NULL;
}
else if (root->left_child == NULL || root->right_child == NULL){
struct node *temp; if
(root->left_child == NULL)
temp = root->right_child;
else
temp = root->left_child;
free(root); return
temp;

}
else {
struct node *temp = find_minimum(root->right_child);
root->data = temp->data;
root->right_child = delete(root->right_child, temp->data);
}
}
return root;
}

void inorder(struct node *root)


{ if (root != NULL)
{
inorder(root->left_child);
printf(" %d ", root->data);
inorder(root->right_child);
}
}

int main() { struct


node *root; root =
new_node(20);
insert(root, 5);
insert(root, 1);
insert(root, 15);
insert(root, 9);
insert(root, 7);
insert(root, 12);
insert(root, 30);
insert(root, 25);
insert(root, 40);
insert(root, 45);
insert(root, 42);
printf("The unsorted root is: \n");
inorder(root); printf("\n");
root = delete(root, 1); root =
delete(root, 40); root =
delete(root, 45); root =
delete(root, 9);
printf("After deletion and sorting the BST becomes: \n");
inorder(root); printf("\n"); return 0;

Program 7
Aim:
Program to illustrate the traversal of graph using BFS.
Code:
#include <stdio.h>
int n, i, j, visited[10], queue[10], front = -1, rear = -
1; int adj[10][10]; void bfs(int v)
{
for (i = 1; i <= n; i++) if
(adj[v][i] && !visited[i])
queue[++rear] = i; if (front
<= rear)
{
visited[queue[front]] = 1;
bfs(queue[front++]);
}
}
void main()
{ int
v;
printf("Enter the number of vertices: ");
scanf("%d", &n); for (i = 1; i <= n; i++)

{
queue[i] = 0;
visited[i] = 0;
}
printf("Enter graph data in matrix form: \
n"); for (i = 1; i <= n; i++) for (j = 1; j <= n;
j++) scanf("%d", &adj[i][j]);
printf("Enter the starting vertex: ");
scanf("%d", &v); bfs(v);
printf("The node which are reachable are: \n");
for (i = 1; i <= n; i++) if (visited[i])
printf("%d\t", i); else
printf("BFS is not possible. Not all nodes are reachable");
return 0;
}
Program 8
Aim:
Program to illustrate the traversal of graph using DFS
Code:
#include <stdio.h>
#include <stdlib.h>

struct node { int


vertex; struct
node* next;
};
struct node* createNode(int
v); struct Graph { int
totalVertices; int* visited;
struct node** adjLists;
};
void DFS(struct Graph* graph, int vertex)
{ struct node* adjList = graph-
>adjLists[vertex]; struct node* temp =
adjList; graph->visited[vertex] = 1;
printf("%d -> ", vertex); while (temp != NULL)
{ int connectedVertex = temp->vertex;

if (graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}
struct node* createNode(int v) {
struct node* newNode = malloc(sizeof(struct
node)); newNode->vertex = v; newNode->next =
NULL; return newNode;
}

struct Graph* createGraph(int vertices) { struct


Graph* graph = malloc(sizeof(struct Graph));
graph->totalVertices = vertices;

graph->adjLists = malloc(vertices * sizeof(struct


node*)); graph->visited = malloc(vertices * sizeof(int));
int i;
for (i = 0; i < vertices; i++) { graph-
>adjLists[i] = NULL; graph->visited[i] = 0;
}
return graph;
}
void addEdge(struct Graph* graph, int src, int dest)
{ struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src]; graph-
>adjLists[src] = newNode; newNode =
createNode(src); newNode->next = graph-
>adjLists[dest]; graph->adjLists[dest] = newNode;
}
void displayGraph(struct Graph* graph)
{ int v;
for (v = 1; v < graph->totalVertices; v++)
{ struct node* temp = graph-
>adjLists[v]; printf("\n%d => ", v);
while (temp) { printf("%d, ", temp-
>vertex); temp = temp->next;
}
printf("\n");
}
printf("\n");
}
int main() {
struct Graph* graph =
createGraph(8); addEdge(graph, 1, 5);
addEdge(graph, 1, 2); addEdge(graph,
1, 3); addEdge(graph, 3, 6);
addEdge(graph, 2, 7); addEdge(graph,
2, 4);

printf("\nThe Adjacency List of the Graph is:");


displayGraph(graph);

printf("\nDFS traversal of the graph: \


n"); DFS(graph, 1); return 0;
}

Program 9
Aim:
Program to sort an array of integers in ascending using bubble
sort.
Code
#include <stdio.h>

void bubble_sort(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])
{ int temp = arr[j];
arr[j] = arr[j + 1]; arr[j
+ 1] = temp;
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubble_sort(arr, n); printf("Sorted
array: ");

for (int i = 0; i < n; i++)


{ printf("%d ", arr[i]);
}
return 0;
}
Program 10
Aim:
Program to sort an array of integers in ascending using
Selection sort.
Code
#include <stdio.h>
// function to swap the the position of two
elements void swap(int *a, int *b) { int temp = *a;
*a = *b;
*b = temp;
}
void selectionSort(int array[], int size)
{ for (int step = 0; step < size - 1; step+
+) { int min_idx = step;
for (int i = step + 1; i < size; i++) {
// To sort in descending order, change > to < in this line.
// Select the minimum element in each loop.
if (array[i] < array[min_idx])
min_idx = i;
}
// put min at the correct position
swap(&array[min_idx], &array[step]);
}
}
// function to print an array void
printArray(int array[], int size)
{ for (int i = 0; i < size; ++i)
{ printf("%d ", array[i]);
}
printf("\n");
}
// driver code int
main() {
int data[] = {20, 12, 10, 15, 2}; int
size = sizeof(data) / sizeof(data[0]);
selectionSort(data, size);
printf("Sorted array in Acsending Order:\n");
printArray(data, size);
}

Program to sort an array of integers in ascending using


insertion sort.
Code
#include <stdio.h>
Program 10
Aim:

void insert(int a[], int n) /* function to sort an aay with


insertion sort */
{
int i, j, temp; for
(i = 1; i < n; i++) {
temp = a[i]; j=i
- 1;

while(j>=0 && temp <= a[j]) /* Move the elements greater


than temp to one position ahead from their current position*/
{
a[j+1] = a[j];
j = j-1;
}
a[j+1] = temp;
}
}

void printArr(int a[], int n) /* function to print the array */


{ in
t i;
for (i = 0; i < n; i++)
printf("%d ", a[i]);
}

int main()
{
int a[] = { 12, 31, 25, 8, 32, 17 };
int n = sizeof(a) / sizeof(a[0]);
printf("Before sorting array elements are - \
n"); printArr(a, n); insert(a, n);
printf("\nAfter sorting array elements are - \n");
printArr(a, n);

return 0;
}

Program to sort an array of integers in ascending using radix


sort.
Code

#include <stdio.h>
Program 10
Aim:
// Function to get the largest element from an
array int getMax(int array[], int n) { int max =
array[0]; for (int i = 1; i < n; i++) if (array[i] >
max) max = array[i]; return max;
}

// Using counting sort to sort the elements in the basis of


significant places
void countingSort(int array[], int size, int place)
{ int output[size + 1]; int max = (array[0] /
place) % 10;

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


if (((array[i] / place) % 10) > max)
max = array[i];
}
int count[max + 1];

for (int i = 0; i < max; ++i)


count[i] = 0;

// Calculate count of elements


for (int i = 0; i < size; i++)
count[(array[i] / place) % 10]++;
// Calculate cumulative count
for (int i = 1; i < 10; i++)
count[i] += count[i - 1];

// Place the elements in sorted order


for (int i = size - 1; i >= 0; i--) {
output[count[(array[i] / place) % 10] - 1] = array[i];
count[(array[i] / place) % 10]--;
}

for (int i = 0; i < size; i++)


array[i] = output[i];
}

// Main function to implement radix


sort void radixsort(int array[], int size) {
// Get maximum element int max =
getMax(array, size);

// Apply counting sort to sort elements based on place


value. for (int place = 1; max / place > 0; place *= 10)
countingSort(array, size, place);
}

// Print an array
void printArray(int array[], int size)
{ for (int i = 0; i < size; ++i)
{ printf("%d ", array[i]);
}
printf("\n");
}

// Driver code int


main() {
int array[] = {121, 432, 564, 23, 1, 45, 788};
int n = sizeof(array) / sizeof(array[0]);
radixsort(array, n); printArray(array, n);
}
Program 10
Aim:
Program to sort an array of integers in ascending using merge
sort.
Code
// 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);
}
}

// UTILITY FUNCTIONS
// Function to print an array
void printArray(int A[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", A[i]); printf("\
n");
}

// Driver code int


main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 }; int
arr_size = sizeof(arr) / sizeof(arr[0]);

printf("Given array is \n"); printArray(arr,


arr_size);

mergeSort(arr, 0, arr_size - 1);

printf("\nSorted array is \n");


printArray(arr, arr_size); return 0;
}

Program 10
Aim:
Program to sort an array of integers in ascending using quick
sort.
Code
// 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 Array\n");
printArray(data, n);

// perform quicksort on data


quickSort(data, 0, n - 1);

printf("Sorted array in ascending order: \n");


printArray(data, n);
}
Program 10
Aim :
Program to demonstrate the use of linear search to search a
given element in an array.
Code:
#include <stdio.h> int
main()
{
int array[100], search, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

for (c = 0; c < n; c++)


{
if (array[c] == search) /* If required element is found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}
Program 10
Aim :
Program to demonstrate the use of binary search to search a
given element in an array of ascending order.
Code:
#include <stdio.h>
int binarySearch(int a[], int beg, int end, int val)
{ int mid;
if(end >= beg)
{ mid = (beg + end)/2;
/* if the item to be searched is present at middle */
if(a[mid] == val)
{
return mid+1;
}
/* if the item to be searched is smaller than middle,
then it can only be in left subarray */ else if(a[mid] < val)
{
return binarySearch(a, mid+1, end, val);
}
/* if the item to be searched is greater than middle,
then it can only be in right subarray */
else
{
return binarySearch(a, beg, mid-1, val);
}
}
return -1;
}
int main() {
int a[] = {11, 14, 25, 30, 40, 41, 52, 57, 70}; // given
array int val = 40; // value to be searched int n =
sizeof(a) / sizeof(a[0]); // size of array int res =
binarySearch(a, 0, n-1, val); // Store result printf("The
elements of the array are - "); for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\nElement to be searched is - %d", val);
if (res == -1)
printf("\nElement is not present in the array");
else
printf("\nElement is present at %d position of array", res);
return 0;
}

You might also like