DSA Sorting
DSA Sorting
Branch – DSAI
1.Implement Bubble sort and print the result of Pass 2 and number of swaps in Pass 2
Code:
#include <iostream>
using namespace std;
int main()
{
int arr[8] = {45, 36, 54, 27, 63, 72, 61, 18};
int swap = 0;
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 8 - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
if (i == 1)
{
swap++;
}
}
}
}
cout << "Array after 2 swaps" << endl;
Output:
Code:
#include <iostream>
using namespace std;
int main() {
int data[] = {45,36,54,27,63,72,61,18};
int size = sizeof(data) / sizeof(data[0]);
insertionSort(data, size);
cout << "Array after Pass 4 is :\n";
for (int i = 0; i < size; i++) {
cout << data[i] << " ";
}
cout << endl;
}
Output:
Code:
#include <bits/stdc++.h>
using namespace std;
if (smallest != i)
{
swap(arr[i], arr[smallest]);
heapify(arr, n, smallest);
}
}
heapify(arr, i, 0);
}
}
int main()
{
int arr[] = {45,36,54,27,63,72,61, 18};
int n = sizeof(arr) / sizeof(arr[0]);
heapSort(arr, n);
cout << "Sorted array using minHeap is: "<<endl;
for(auto i:arr){
cout<<i<<" ";
}
}
Output:
MaxHeap
Code:
#include <iostream>
using namespace std;
void heapify(int a[], int n, int i)
{
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (left < n && a[left] > a[largest])
largest = left;
Output: