0% found this document useful (0 votes)
8 views21 pages

01 - Ca2 - Bcac 303

Different array algorithm with outputs

Uploaded by

GAMING
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)
8 views21 pages

01 - Ca2 - Bcac 303

Different array algorithm with outputs

Uploaded by

GAMING
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/ 21

NAME – RAJAT SINGH

CLASS – 2ND YEAR (3RD SEM)


DEPARTMENT – BCA
ROLL NO.- 31401221001
REGISTRATION NO-
213141001210047
SUBJECT – DATA STRUCTURE
LAB(BCAC303)CA2
SUBJECT CODE: bcac303
YEAR:2021-2024

INSERTION OF ARRAY
An array is a collection of items stored at contiguous memory locations. In this
article, we will see how to insert an element in an array in C.
Given an array arr of size n, this article tells how to insert an element x in this
array arr at a specific position pos.
Insertion Sort Algorithm
To sort an array of size N in ascending order:
• Iterate from arr[1] to arr[N] over the array.
• Compare the current element (key) to its predecessor.
• If the key element is smaller than its predecessor, compare it to the
elements before. Move the greater elements one position up to make
space for the swapped element.

// C++ program for insertion sort

#include <bits/stdc++.h>

using namespace std;

// Function to sort an array using

// insertion sort

void insertionSort(int arr[], int n)

int i, key, j;

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

key = arr[i];

j = i - 1;

// Move elements of arr[0..i-1],

// that are greater than key, to one

// position ahead of their

// current position

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

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

j = j - 1;

arr[j + 1] = key;

// A utility function to print an array

// of size n

void printArray(int arr[], int n)

int i;

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

cout << arr[i] << " ";

cout << endl;

// Driver code

int main()

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

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

insertionSort(arr, N);

printArray(arr, N);

return 0;

// This is code is contributed by rathbhupendra


Output
5 6 11 12 13

DELETION OF ARRAY
Algorithm to Delete an element from an Array:

• Step 01: Start


• Step 02: [Initialize counter variable. ] Set i = pos - 1

• Step 03: Repeat Step 04 and 05 for i = pos - 1 to i < size

• Step 04: [Move ith element backward (left). ] set a[i] = a[i+1]

• Step 05: [Increase counter. ] Set i = i + 1

• Step 06: [End of step 03 loop. ]


• Step 07: [Reset size of the array. ] set size = size - 1

• Step 08: Stop

Implementation in C:

1// writing a program in C to delete an element from an array


2
3void main()
4{
5 int i, size, pos;
6 int a[]={2, 4, 6, 8, 12};
7 size=sizeof(a)/sizeof(a[0]);
printf("The array elements before deletion operation:\n");
8
for(i=0;i<size;i++)
9
printf("a[%d] = %d\n", i, a[i]);
10
printf("Enter the position from where you wish to delete the element: ");
11 scanf("%d", &pos);
12 printf("The array elements after deletion operation:\n");
13 for(i=pos-1;i<size;i++)
14 a[i]=a[i+1];
15 size = size - 1;
16 for(i=0;i<size;i++)
17 printf("a[%d] = %d\n", i, a[i]);
18}
19

Output:

1
2The array elements before deletion operation:
3a[0] = 2
4a[1] = 4
a[2] = 6
5
a[3] = 8
6a[4] = 12
7Enter the position from where you wish to delete the element: 3
8The array elements after deletion operation:
9a[0] = 2
10a[1] = 4
11a[2] = 8
12a[3] = 12

LINEAR SEARCH ALGORITHM


Linear_Search ( Array X, Value i)

• Set j to 1
• If j > n, jump to step 7
• If X[j] == i, jump to step 6
• Then, increment j by 1 i.e. j = j+1
• Go back to step 2
• Display the element i which is found at particular index i, then jump to step
8
• Display element not found in the set of input elements.
• Exit/End

#include <stdio.h>

int LINEAR_SEARCH(int inp_arr[], int size, int val)


{
for (int i = 0; i < size; i++)
if (inp_arr[i] == val)
return i;
return -1;
}

int main(void)
{
int arr[] = { 10, 20, 30, 40, 50, 100, 0 };
int key = 100;
int size = 10;
int res = LINEAR_SEARCH(arr, size, key);
if (res == -1)
printf("ELEMENT NOT FOUND!!");
else
printf("Item is present at index %d", res);

return 0;
}

Output:

Item is present at index 5

BINARY SEARCH ALGORITHM


1. Binary_Search(a, lower_bound, upper_bound, val) // 'a' is the given array, 'lower_b
ound' is the index of the first array element, 'upper_bound' is the index of the last
array element, 'val' is the value to search
2. Step 1: set beg = lower_bound, end = upper_bound, pos = - 1
3. Step 2: repeat steps 3 and 4 while beg <=end
4. Step 3: set mid = (beg + end)/2
5. Step 4: if a[mid] = val
6. set pos = mid
7. print pos
8. go to step 6
9. else if a[mid] > val
10. set end = mid - 1
11. else
12. set beg = mid + 1
13. [end of if]
14. [end of loop]
15. Step 5: if pos = -1
16. print "value is not present in the array"
17. [end of if]
18. Step 6: exit

Write a program to implement Binary search in C++.

1. #include <iostream>
2. using namespace std;
3. int binarySearch(int a[], int beg, int end, int val)
4. {
5. int mid;
6. if(end >= beg)
7. {
8. mid = (beg + end)/2;
9. /* if the item to be searched is present at middle */
10. if(a[mid] == val)
11. {
12. return mid+1;
13. }
14. /* if the item to be searched is smaller than middle, then it can only be in l
eft subarray */
15. else if(a[mid] < val)
16. {
17. return binarySearch(a, mid+1, end, val);
18. }
19. /* if the item to be searched is greater than middle, then it can only be in rig
ht subarray */
20. else
21. {
22. return binarySearch(a, beg, mid-1, val);
23. }
24. }
25. return -1;
26. }
27. int main() {
28. int a[] = {10, 12, 24, 29, 39, 40, 51, 56, 70}; // given array
29. int val = 51; // value to be searched
30. int n = sizeof(a) / sizeof(a[0]); // size of array
31. int res = binarySearch(a, 0, n-1, val); // Store result
32. cout<<"The elements of the array are - ";
33. for (int i = 0; i < n; i++)
34. cout<<a[i]<<" ";
35. cout<<"\nElement to be searched is - "<<val;
36. if (res == -1)
37. cout<<"\nElement is not present in the array";
38. else
39. cout<<"\nElement is present at "<<res<<" position of array";
40. return 0;
41. }

OUTPUT:

Bubble Sort Algorithm


First Pass:
• Bubble sort starts with very first two elements, comparing them to
check which one is greater.
• ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the
first two elements, and swaps since 5 > 1.
• ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4
• ( 1 4 5 2 8 ) –> ( 1 4 2 5 8 ), Swap since 5 > 2
• ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are
already in order (8 > 5), algorithm does not swap them.
Second Pass:
• Now, during second iteration it should look like this:
• ( 1 4 2 5 8 ) –> ( 1 4 2 5 8 )
• ( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
Third Pass:
• Now, the array is already sorted, but our algorithm does not know if it
is completed.
• The algorithm needs one whole pass without any swap to know it is
sorted.
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
• ( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

• / C++ program for implementation


• // of Bubble sort
• #include <bits/stdc++.h>
• using namespace std;

• // A function to implement bubble sort
• void bubbleSort(int arr[], int n)
• {
• int i, j;
• for (i = 0; i < n - 1; i++)

• // Last i elements are already
• // in place
• for (j = 0; j < n - i - 1; j++)
• if (arr[j] > arr[j + 1])
• swap(arr[j], arr[j + 1]);
• }

• // Function to print an array
• void printArray(int arr[], int size)
• {
• int i;
• for (i = 0; i < size; i++)
• cout << arr[i] << " ";
• cout << endl;
• }

• // Driver code
• int main()
• {
• int arr[] = { 5, 1, 4, 2, 8};
• int N = sizeof(arr) / sizeof(arr[0]);
• bubbleSort(arr, N);
• cout << "Sorted array: \n";
• printArray(arr, N);
• return 0;
• }

Output
Sorted array:
1 2 4 5 8

SELECTION SORT ALGORITHM


he selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the
beginning. The algorithm maintains two subarrays in a given array.
• The subarray which is already sorted.
• Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending
order) from the unsorted subarray is picked and moved to the sorted subarray.
Lets consider the following array as an example: arr[] = {64, 25, 12, 22,
11}
First pass:
• For the first position in the sorted array, the whole array is
traversed from index 0 to 4 sequentially. The first position
where 64 is stored presently, after traversing whole array it is
clear that 11 is the lowest value.
64 25 12 22 11
• Thus, replace 64 with 11. After one iteration 11, which happens to
be the least value in the array, tends to appear in the first position
of the sorted list.
11 25 12 22 64
Second Pass:
• For the second position, where 25 is present, again traverse the
rest of the array in a sequential manner.
11 25 12 22 64
• After traversing, we found that 12 is the second lowest value in
the array and it should appear at the second place in the array,
thus swap these values.
11 12 25 22 64
Third Pass:
• Now, for third place, where 25 is present again traverse the rest
of the array and find the third least value present in the array.
11 12 25 22 64
• While traversing, 22 came out to be the third least value and it
should appear at the third place in the array, thus swap 22 with
element present at third position.
11 12 22 25 64
Fourth pass:
• Similarly, for fourth position traverse the rest of the array and find
the fourth least element in the array
• As 25 is the 4th lowest value hence, it will place at the fourth
position.
11 12 22 25 64
Fifth Pass:
• At last the largest value present in the array automatically get placed
at the last position in the array
• The resulted array is the sorted array.
11 12 22 25 64

/ C program for implementation of selection sort


#include <stdio.h>

void swap(int *xp, int *yp)


{
int temp = *xp;
*xp = *yp;
*yp = temp;
}

void selectionSort(int arr[], int n)


{
int i, j, min_idx;

// One by one move boundary of unsorted subarray


for (i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first element


if(min_idx != i)
swap(&arr[min_idx], &arr[i]);
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver program to test above functions


int main()
{
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

output
Sorted array:
11 12 22 25 64
\\

INSERTION SORT ALGORITHM


Step 1. If there is only one element or the first element in an array, it

behaves as a sorted array.

Step 2. Now pick the new element which you want to insert.

Step 3. Compare the new picked element with the sorted element of an

array.

Step 4. Insert the value if the correct position is found.

Step 5. Repeat step 2 to step 4 until all element is inserted in an array.


Insertion Sort Program in C
1
2
3#include&lt;stdio.h&gt;
4#include&lt;conio.h&gt;
5void main(){
int arr[100],i,j,n,key;
6
printf("Enter the number of elements you want to sort:\n");
7
scanf("%d",&amp;n);
8 printf("Now enter the %d elements you want to sort: \n",n);
9 for(i=0;i&lt;n;i++){
10 scanf("%d",&amp;arr[i]);
11 }
12 printf("before sorting:\n");
13 for(i=0;i&lt;n;i++){
14 printf("%d \t",arr[i]);
15 }
16 for(i=1;i&lt;n;i++){
17 key=arr[i];
18 j=i-1;
19 while(j&gt;=0 &amp;&amp; arr[j]&gt;key){
20 arr[j+1]=arr[j];
j=j-1;
21
}
22
arr[j+1]=key;
23
}
24 printf("\n");
25 printf("after sorting:\n");
26 for(i=0;i&lt;n;i++){
27 printf("%d\t",arr[i]);
28 }
29 getch();
30}

OUTPUT:
MERGE SORT ALGORITHM
In the following algorithm, arr is the given array, beg is the starting element, and end is
the last element of the array.

1. MERGE_SORT(arr, beg, end)


2.
3. if beg < end
4. set mid = (beg + end)/2
5. MERGE_SORT(arr, beg, mid)
6. MERGE_SORT(arr, mid + 1, end)
7. MERGE (arr, beg, mid, end)
8. end of if
9.
10. END MERGE_SORT

PROGRAM: WRITE A PROGRAM TO IMPLEMENT MERGE SORT IN C


LANGUAGE.

1. #include <stdio.h>
2.
3. /* Function to merge the subarrays of a[] */
4. void merge(int a[], int beg, int mid, int end)
5. {
6. int i, j, k;
7. int n1 = mid - beg + 1;
8. int n2 = end - mid;
9.
10. int LeftArray[n1], RightArray[n2]; //temporary arrays
11.
12. /* copy data to temp arrays */
13. for (int i = 0; i < n1; i++)
14. LeftArray[i] = a[beg + i];
15. for (int j = 0; j < n2; j++)
16. RightArray[j] = a[mid + 1 + j];
17.
18. i = 0; /* initial index of first sub-array */
19. j = 0; /* initial index of second sub-array */
20. k = beg; /* initial index of merged sub-array */
21.
22. while (i < n1 && j < n2)
23. {
24. if(LeftArray[i] <= RightArray[j])
25. {
26. a[k] = LeftArray[i];
27. i++;
28. }
29. else
30. {
31. a[k] = RightArray[j];
32. j++;
33. }
34. k++;
35. }
36. while (i<n1)
37. {
38. a[k] = LeftArray[i];
39. i++;
40. k++;
41. }
42.
43. while (j<n2)
44. {
45. a[k] = RightArray[j];
46. j++;
47. k++;
48. }
49. }
50.
51. void mergeSort(int a[], int beg, int end)
52. {
53. if (beg < end)
54. {
55. int mid = (beg + end) / 2;
56. mergeSort(a, beg, mid);
57. mergeSort(a, mid + 1, end);
58. merge(a, beg, mid, end);
59. }
60. }
61.
62. /* Function to print the array */
63. void printArray(int a[], int n)
64. {
65. int i;
66. for (i = 0; i < n; i++)
67. printf("%d ", a[i]);
68. printf("\n");
69. }
70.
71. int main()
72. {
73. int a[] = { 12, 31, 25, 8, 32, 17, 40, 42 };
74. int n = sizeof(a) / sizeof(a[0]);
75. printf("Before sorting array elements are - \n");
76. printArray(a, n);
77. mergeSort(a, 0, n - 1);
78. printf("After sorting array elements are - \n");
79. printArray(a, n);
80. return 0;
81. }
OUTPUT:

QUICK SORT ALGORITHM


Quicksort is a divide and conquer algorithm.
It divides the large array into smaller sub-arrays. And then quicksort recursively sort
the sub-arrays.

Pivot
1. Picks an element called the "pivot".

Partition
2. Rearrange the array elements in such a way that the all values lesser than the
pivot should come before the pivot and all the values greater than the pivot should
come after it.
This method is called partitioning the array. At the end of the partition function, the
pivot element will be placed at its sorted position.

Recursive
3. Do the above process recursively to all the sub-arrays and sort the elements.

Base Case
If the array has zero or one element, there is no need to call the partition method.
So we need to stop the recursive call when the array size is less than or equal to 1.

program: Write a program to implement quick sort in C++ language.

1. #include <iostream>
2.
3. using namespace std;
4.
5. /* function that consider last element as pivot,
6. place the pivot at its exact position, and place
7. smaller elements to left of pivot and greater
8. elements to right of pivot. */
9. int partition (int a[], int start, int end)
10. {
11. int pivot = a[end]; // pivot element
12. int i = (start - 1);
13.
14. for (int j = start; j <= end - 1; j++)
15. {
16. // If current element is smaller than the pivot
17. if (a[j] < pivot)
18. {
19. i++; // increment index of smaller element
20. int t = a[i];
21. a[i] = a[j];
22. a[j] = t;
23. }
24. }
25. int t = a[i+1];
26. a[i+1] = a[end];
27. a[end] = t;
28. return (i + 1);
29. }
30.
31. /* function to implement quick sort */
32. void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting in
dex, end = Ending index */
33. {
34. if (start < end)
35. {
36. int p = partition(a, start, end); //p is the partitioning index
37. quick(a, start, p - 1);
38. quick(a, p + 1, end);
39. }
40. }
41.
42. /* function to print an array */
43. void printArr(int a[], int n)
44. {
45. int i;
46. for (i = 0; i < n; i++)
47. cout<<a[i]<< " ";
48. }
49. int main()
50. {
51. int a[] = { 23, 8, 28, 13, 18, 26 };
52. int n = sizeof(a) / sizeof(a[0]);
53. cout<<"Before sorting array elements are - \n";
54. printArr(a, n);
55. quick(a, 0, n - 1);
56. cout<<"\nAfter sorting array elements are - \n";
57. printArr(a, n);
58.
59. return 0;
60. }

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy